Using Disposable Windows SharePoint Services Objects

During my last project on MS CRM 4.0, I had to integrate SharePoint and MSCRM. This majorly involved creation of a web part for data analysis. During the development, I encountered scenarios facing long term retention of share point objects in memory.

Memory leak is one of the major problems that can arise due to bad coding practices. Disposing the used SharePoint Objects is one of the best practices while coding in SharePoint. Here, I have explained why, how and when to dispose off the SP Objects in code.


The objects in the Windows SharePoint Services 3.0 object model serve as an interface for working with Windows SharePoint Services data. The developers frequently call into the object model to read data from or write new data to the Windows SharePoint Services store.
The Windows SharePoint Services object model contains objects that implement the IDisposable interface. One must take precautions when using these objects to avoid their long-term retention in memory in the Microsoft .NET Framework.
Specifically, one should explicitly dispose of those SharePoint objects that implement IDisposable after using them.

Why Dispose is required?
Several of the Windows SharePoint Services objects, primarily the SPSite class and SPWeb class objects, are created as managed objects. However, these objects use unmanaged code and memory to perform the majority of their work. The managed part of the object is much smaller than the unmanaged part. Because the smaller managed part does not put memory pressure on the garbage collector, the garbage collector does not release the object from memory in a timely manner. The object's use of a large amount of unmanaged memory can cause some of the unusual behaviors described earlier. Calling applications that work with IDisposable objects in Windows SharePoint Services must dispose of the objects when the applications finish using them. You should not rely on the garbage collector to release them from memory automatically.

Coding Techniques to Ensure Object Disposal

One can employ certain coding techniques to ensure object disposal. These techniques include using the following in your code:
• Dispose method
• using clause
• try, catch, and finally blocks

The using Clause:
Automatically dispose of SharePoint objects that implement the IDisposable interface by using the Microsoft Visual C# using statement.

using(SPSite oSPsite = new SPSite("http://server"))
{
using(SPWeb oSPWeb = oSPSite.OpenWeb())
{
String str = oSPWeb.Title;
str = oSPWeb.Url;
} //SPWeb object is disposed automatically
} // SPSite object is disposed automatically


The try, catch, and finally Blocks

Using try, catch, and finally blocks obviously makes sense whenever you need to handle exceptions. Any code within a try/catch block should have a governing finally clause to ensure that the objects that implement IDisposable are disposed. Never leave a catch block empty. Also note the best practice of testing for null before disposing.

String str;
SPSite oSPSite = null;
SPWeb oSPWeb = null;
try
{
oSPSite = new SPSite("http://server");
oSPWeb = oSPSite.OpenWeb(..);

str = oSPWeb.Title;
}
catch(Exception e)
{ //Handle exception, log exception, etc.
}
finally
{
if (oSPWeb != null)
oSPWeb.Dispose();

if (oSPSite != null)
oSPSite.Dispose();
}


Note: SPContext objects are managed by the SharePoint framework and should not be explicitly disposed in code. This is true also for the SPSite and SPWeb objects returned by SPContext.Site, SPContext.Current.Site, SPContext.Web, and SPContext.Current.Web.

Recommendations to Reduce Long-Term Object Retention

You can reduce long-term retention of SharePoint objects by following these general recommendations:-

• While creating an object with a new operator, ensure that the creating application disposes it off.

Explicitly Disposing
void CreatingSPSiteExplicitDisposeNoLeak()
{
SPSite siteCollection = null;
try
{
siteCollection = new SPSite("http://moss");
}
finally
{
if (siteCollection != null)
siteCollection.Dispose();
}
}


Automatically Disposing
void CreatingSPSiteWithAutomaticDisposeNoLeak()
{
using (SPSite siteCollection = new SPSite("http://moss"))
{
} // SPSite object siteCollection.Dispose() is called automatically.
}

• Dispose of items created by SharePoint methods that return other SPWeb objects (such as OpenWeb).

• Do not share any SPRequest object (and by extension any object that contains a reference to an SPRequest object) across threads. Any coding technique that shares a SPRequest object between two or more threads, or creates a SPRequest object on one thread and disposes it on another, is not supported. This means that any object that holds a reference to a SPRequest object in a static variable cannot be stored. Thus, Do not store SharePoint objects that implement IDisposable (such as SPWeb orSPSite) in static variables.

For Reference, SharePoint Dispose Checker Tool, is a free tool available as a download that inspects assemblies for coding practices that cause memory leaks because of improper handling and disposal of SharePoint objects.

Soon I will post another article on How To Find Incorrectly Disposed Objects.

Comments

  1. I am satisfied that you simply shared this useful information with us.
    Please stay us informed like this. Thanks for sharing.
    Microsoft Dynamics CRM Online Training | Sharepoint Training

    ReplyDelete

Post a Comment

Popular posts from this blog

IFD Implementation for custom web pages and Anonymous Access

Using CRM Services to create or update records in large numbers

Issues after Re-Naming MS CRM Servers computer/machine name