Microsoft

Blog Categories

Subscribe to RSS feed

Archives

I Dispose So…

What goes up must come down. The same idea pertains to what is created, generally must be disposed of. The issue of garbage collection has always plagued programmers in just about every programming language. SharePoint has implemented automatic garbage disposal in a few ways. Still, a conscious effort for disposal must be made in many situations.

The SPSite and SPWeb objects use resources that need to be disposed of properly once their purpose no longer exists. If not disposed, those objects could potentially cause memory leaks resulting in instable environments.

Now the question is, when do I explicitly call the dispose method and when does SharePoint do it for me? There are quite a few situations where you will have to explicitly dispose objects and you can find the full set of instances here, but I will provide you with the most common situations I have come across:

  1. DISPOSE whenever you instantiate SPSite and SPWeb objects with the new operator. You have to make sure those objects are properly disposed by explicitly calling the dispose method.

    SPSite siteCollection = new SPSite("http://site1/");

    [...]

    siteCollection.Dispose();

  2. DISPOSE objects created when you indirectly call a property or a method of another object that reference a SPSite or SPWeb object. The RootWeb property and the OpenWeb method are good examples as both return SPWeb objects. You have to make sure you dispose of those objects as well.

    SPSite siteCollection = new SPSite("http://site1/");

    SPWeb web = siteCollection.RootWeb;

    Web.Dispose();

    siteCollection.Dispose();

  3. DO NOT DISPOSE if you do decide to use the SPContext.Current.Site and SPContext.Current.Web objects. Sometimes, it is not necessary to create objects using the new operator when the context of the current request could be used instead. Keep in mind that you won’t have to dispose of those objects yourself as SharePoint will do it automatically for you after the page has been processed.

    SPSite siteCollection = SPContext.Current.Site;

  4. DO NOT DISPOSE site and web objects if they are wrapped within a using statement because the dispose method will automatically be called when they exit the using statement. The using statement.

    Using (SPSite siteCollection = new SPSite(http://site1/))

    {

    […]

    }

Make sure you also visit the msdn best practices for disposing objects.

Leave a Reply