Thursday, November 12, 2009

Trying to use an SPWeb object that has been closed or disposed and is no longer valid

You receive the above error while trying to edit a WebPart page which uses a custom WebPart with SharePoint API. As per the best practices recommendation, some of the WSS objects like SPWeb & SPSite need to be disposed programmatically to avoid memory leaks as they use unmanaged code and memory to perform their operation. In C# the best way is to use “using” statement for this purpose as the common language runtime translates using clauses into try and finally blocks, and any objects that implement the IDisposable interface are disposed for you.

However, there are some special cases where you should not dispose the object programmatically. The following code example shows one case where you would not want the runtime to construct a finally block and dispose objects for you


using( SPWeb web = SPControl.GetContextWeb(HttpContext.Current)) { ... }


This is because SPContext objects are managed by the SharePoint framework and should not be explicitly disposed in your code. This is true also for the SPSite and SPWeb objects returned by SPContext.Site, SPContext.Current.Site, SPContext.Web, and SPContext.Current.Web.

You receive the “Trying to use an SPWeb object that has been closed or disposed and is no longer valid” when page is in edit mode if you tried to dispose SPContext retrieved objects.

http://msdn.microsoft.com/en-us/library/aa973248.aspx