Aidan Garnish

Collaboration Not Competition

Trouble shooting SPWeb object closed or disposed

I recently came across an issue on a WCM site where the following error was being shown whenever a dropdown selection was changed on a custom web part:
SPException: Trying to use an SPWeb object that has been closed or disposed and is no longer valid 

This looked like the SPWeb object was being incorrectly disposed of but careful inspection of the web part showed that best practices for disposal of SPObjects had been followed .
To try and track down the cause of the error and to really satisfy myself that it wasn't the web part causing the issue I removed all references to SPWeb from the custom web part. The error was still appearing so this ruled out bad coding practice in this control.
The next step was to take a look at the other controls on the page. As this was a WCM site there were a number of custom controls being used for navigation and other functionality.
It didn't take too long to track down the culprit in a control being used to set the site title in the browser title bar. This contained the following:
using(SPWeb web = SPContext.Current.Web)
   //some code
When the dropdown selection was changed a postback was fired and this piece of code brought the site crashing down.
This was because both the using statement and the use of SPContext handle garbage collection so the SPWeb object was being disposed of twice and as it didn't exist on the second dispose the error above was thrown.
Once corrected the code looked like this:
SPWeb web = SPContext.Current.Web;
//some code 

Most of the links about this error on the web will point you towards the issue being incorrect disposal of objects but what is learnt here is that it might not be a coding issue in the control that seems to be causing the problem. In this case it was the postback being fired by the control rather than the control itself that was triggering the error. The root cause was actually a completely different web part on the page.

Add comment