Diffrent Ways to Implement Dispose Patterns/Methods in Your SharePoint Code

Introduction

It’s very important to dispose our objects in SharePoint to avoid Memory Leaks, this article will explain dispose Patterns or methods in SharePoint code.

Method 1 - Manually calling Dispose()

The most general and simple approach to dispose your objects is to simply call the .Dispose() method of your objects:
  1. SPSite site = new SPSite ("http://laxman-sharepoi:1000/admin/");  
  2.   
  3. // Do stuff   
  4.   
  5. site.Dispose();  
Method 2 - Encapsulating the statement in a using() block

A more common approach is to encapsulate the code in a using-block where the object will be automatically disposed when we are reaching the end of our block.
  1. using (SPSite site = new SPSite ("http://laxman-sharepoi:1000/admin/"));  
  2.   
  3. {  
  4.   
  5.       // Do stuff   
  6.   
  7. }    
Method 3 - Utilize a try/finally block

Whenever you are expecting to catch an exception and need to handle them – a better approach for disposing is to create a try-finally block and dispose the object in the finally-block.

Sample 1: Without exception handling.
  1. SPSite site = null ;  
  2.   
  3. try   
  4.   
  5. {  
  6.   
  7.       site = new SPSite ("http://laxman-sharepoi:1000/admin/");  
  8.   
  9.       // do stuff   
  10.   
  11. }  
  12.   
  13. finally   
  14.   
  15. {  
  16.   
  17.       if (site!=null ) site.Dispose();   
  18.   
  19. }      
Sample 2: With exception handling.
  1. SPSite site = null ;  
  2.   
  3. try   
  4.   
  5. {  
  6.   
  7.       site = new SPSite ("http://laxman-sharepoi:1000/admin/");  
  8.   
  9.       // do stuff   
  10.   
  11. }  
  12.   
  13. catch (Exception ex)  
  14.   
  15. {  
  16.   
  17.       // Handle the exception   
  18.   
  19.       // Possibly genrate logs  
  20.   
  21. }  
  22.   
  23. finally   
  24.   
  25. {  
  26.   
  27.       if (site!=null ) site.Dispose();  
  28.   
  29. }  
Method 4 - A mix mode approach

In some scenarios it might be a necessity to use mix oapproach for disposing.
  1. using (SPSite site = new SPSite ("http://laxman-sharepoi:1000/admin/"))  
  2.   
  3. {  
  4.   
  5.       foreach (SPSite site in site.WebApplication.Sites)  
  6.   
  7.       {  
  8.   
  9.             try   
  10.   
  11.             {  
  12.   
  13.                   // Do stuff   
  14.         
  15.             }  
  16.   
  17.             catch (Exception ex)  
  18.   
  19.             {  
  20.   
  21.                   // Log and handle exceptions   
  22.   
  23.             }  
  24.   
  25.             finally   
  26.   
  27.             {  
  28.   
  29.                   if (site!=null ) site.Dispose();  
  30.   
  31.             }  
  32.   
  33.       }  
  34.   
  35. }  
Ebook Download
View all
Learn
View all