Bluedog Limited > SharePoint Thoughts > Posts > Dispose your SPSite and SPWeb objects - Part II - Knowing when not to
May 31
Dispose your SPSite and SPWeb objects - Part II - Knowing when not to
This post was migrated from an older system. Some links may point to content that no longer exists. Comments were not migrated.

Last August I wrote a small article that advocated the benefits of using the Close() and Dispose() methods of both the SPSite and SPWeb classes.  In particular, the article was written with executables in mind and not web parts and controls.  In most cases, the technique of using a “using” or explicitly calling the corresponding disposal methods is exactly what you want to do. 

There is one case, however, where you *should not* call the disposal methods.  It all depends on how your SPSite and SPWeb objects are created.

// Example of what *not* to do...
using (SPSite site = SPControl.GetContextSite (this.Context)) {
  // Code to do cool stuff...
}
 
// If you need to use GetContext*, let SharePoint dispose of
// the object.  It’s a shared resource...
SPSite site = SPControl.GetContextSite (this.Context);
  // Code to do cool stuff...
// site.Dispose ();  <-- Don’t call Dispose/Close on a shared resource. Leave this line commented!

The bottom line is that if you create your own objects; feel free to dispose of them.  If you get a reference to a shared resource such as the objects provided by the GetContext* methods, don’t dispose the objects yourself – let SharePoint manage the objects.  Otherwise, you may run into situations where the shared resource has already been disposed (and therefore is unavailable).

Why is this important to call out now?  The SDK documentation doesn’t readily illustrate the behavior of the GetContext* methods.  As a result, more and more folks are bumping into problems as the one illustrated by a reader’s comment in the original article.  Sometimes failures are seen, sometimes they are not.  It’s really a timing issue that depends on when and how other controls on the page attempt to use the shared resource. 

The documentation will improve; either as a KB or a simple addition to the SDK.  In the meantime, know when to dispose your objects... and you’ll avoid random failures and crashes. 

-Maurice

Comments

There are no comments for this post.

Add Comment

Items on this list require content approval. Your submission will not appear in public views until approved by someone with proper rights. More information on content approval.

Title


Body *


captcha

Please verify the text shown in the image

Attachments


© Bluedog Limited 2004-2012
Aptillon, Inc.
Microsoft Certified Master - SharePoint 2010 & 2007
Sign In