SharePoint Best Practices - COM Objects Disposal

While writing the code with SharePoint Server Side Object Model, I an often stuck with a question “What objects, should I be responsible for disposing of?”

Though this seems to be a simple question I found it worth researching to extract the list of all the objects for which a developer is responsible to dispose  of in order to avoid any memory leaks in the Farm.

In order to simplify the story, I have divided SharePoint objects in the three categories given below.

List of objects, which must be disposed explicitly

  1. SPWeb Object created with SPSite.OpenWeb.
  2. SPSite objects created with SPSite.SelfServiceCreateSite.
  3. SPWeb created by SPLimitedWebPartManager.
  4. SPSite created by SPSiteCollection.Add.
  5. SPSite created by SPSiteCollection[] index operator.
  6. SPWeb created by SPWebCollection.Add.
  7. SPWeb created by SPWebCollection[] index operator.
  8. SPSite created with UserProfiles.PersonalSite.

List of objects, which must be closed (not disposed) explicitly:

  1. PublishingWeb created by PublishingWeb.GetPublishingWebs[] index operator.
  2. PublishingWeb created by PublishingWeb.GetVariation.
  3. PublishingWeb created by PublishingWebCollection.Add.

List of objects, which must never be disposed explicitly

  1. SPListEventProperties.Web.
  2. SPWebEventProperties.Web.
  3. SPItemEventProperties.Web.
  4. SPItemEventProperties.ListItem.Web.
  5. SPItemEventProperties.Web.Site.
  6. SPItemEventProperties.ListItem.Web.Site.
  7. SPFeatureReceiverProperties.Feature.Parent.
  8. SPSite.RootWeb.
  9. SPWeb.ParentWeb.
  10. SPList.ParentWeb.
  11. SPSite returned by SPControl.GetContextSite.
  12. SPWeb returned by SPControl.GetContextWeb.
  13. SPSite returned by SPContext.Current.Site.
  14. SPWeb returned by SPContext.Current.Web.

How to ensure proper disposal of an object after the job is done

There are the following two constructs available, which can ensure the disposal of SharePoint objects even if any unforeseen runtime exception occurs in the code.

1. Use “Using Block”.

  1. using(SPWeb oWeb = osite.RootWeb)  
  2. {  
  3. }//oWeb will get disposed automatically as soon as using block ends  

2. Use “Try, Catch & Finally Block”. 

  1. try {  
  2.     SPWeb oWeb = osite.RootWeb;  
  3. catch (Exception ex) {  
  4.     throw;  
  5. finally {  
  6.     oWeb.Dispose(); //oWeb will get disposed as soon as Dispose() method called.  
  7. }  

Hope, you find it helpful.

Up Next
    Ebook Download
    View all
    Learn
    View all