Friday, 15 June 2007

Disposing of SPSite and SPWeb Objects

Wherever you use the SPWeb and SPSite objects, you must always dispose them after use. You can do this by either explicitly disposing of the by calling the dispose method, or encasing them in a "using" statement, "scope".  .If you do not dispose of the objects then memory can quickly be consumed and eventually, dependent on the scale of your architecture, your environment will grind to a halt.

So how do we Dispose or Scope ?  Bear in mind that both of these methods are as efficient as each other.

Dispose SPSite and SPWeb

There are 2 scenarios where you must be disposing of the SPSite and SPWeb objects. The first is a general assignment scenario, which is disposing of the SPSite and SPWeb objects directly. The second is the one that is usually missed and more critical in causing memory leaks which involves the use of the SPWeb object within a Foreach loop.  both are documented below.

General dispose after use, I have been also enclosed this in a try, catch, finally statement to enable greater exception handling.

Code Snippet
  1. SPSite site = null;
  2. SPWeb web = null;
  3. try
  4. {
  5.     site = new SPSite("http://mysite.com/sitecollection");
  6.     web = site.OpenWeb("mysitename");
  7.  
  8.     //other code here
  9. }
  10. finally
  11. {
  12.     web.Dispose();
  13.     site.Dispose();
  14. }

Disposing of SPWeb in foreach loop.  the subWeb object in the code below is explicitly disposed of.

Code Snippet
  1. SPSite site = new SPSite("http://mysite.com/sitecollection");
  2. SPWebCollection allWebs = site.AllWebs;
  3. foreach (SPWeb web in allWebs)
  4. {
  5.     //other code here
  6.     web.Dispose();
  7. }
  8.  
  9. site.Dispose();

Scope SPSite and SPWeb

Within your assignment of the SPSite and SPWeb objects, encase them in a using statement. This will dispose of the objects once the scope of the code runs outside the using scope.

Code Snippet
  1. using (SPSite site = new SPSite("http://mysite.com/sitecollection"))
  2. {
  3.     using (SPWeb web = site.OpenWeb("mysitename"))
  4.     {
  5.         //other code here
  6.     }
  7. }

if you use a foreach loop within the using statement, the subwebs will still have to be disposed of explicitly.

0 comments:

Post a Comment