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:
- SPSite site = new SPSite ("http://laxman-sharepoi:1000/admin/");
-
-
-
- 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.
- using (SPSite site = new SPSite ("http://laxman-sharepoi:1000/admin/"));
-
- {
-
-
-
- }
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.
- SPSite site = null ;
-
- try
-
- {
-
- site = new SPSite ("http://laxman-sharepoi:1000/admin/");
-
-
-
- }
-
- finally
-
- {
-
- if (site!=null ) site.Dispose();
-
- }
Sample 2: With exception handling.
- SPSite site = null ;
-
- try
-
- {
-
- site = new SPSite ("http://laxman-sharepoi:1000/admin/");
-
-
-
- }
-
- catch (Exception ex)
-
- {
-
-
-
-
-
- }
-
- finally
-
- {
-
- if (site!=null ) site.Dispose();
-
- }
Method 4 - A mix mode approach
In some scenarios it might be a necessity to use mix oapproach for disposing.
- using (SPSite site = new SPSite ("http://laxman-sharepoi:1000/admin/"))
-
- {
-
- foreach (SPSite site in site.WebApplication.Sites)
-
- {
-
- try
-
- {
-
-
-
- }
-
- catch (Exception ex)
-
- {
-
-
-
- }
-
- finally
-
- {
-
- if (site!=null ) site.Dispose();
-
- }
-
- }
-
- }