Using Disposable Objects (SharePoint Best Practices)

Question:
Why do we need to dispose objects we create?
Most often we tend to write Unmanaged code inside managed code. Managed Objects created from such Managed classes as SPSite and SPWeb
has very little to do with the unmanaged code sitting inside their boundary. Now, when you compare this size of the managed part is considerably
lesser than that of the unmanaged part, GC would ignore mostly and doesnt clear the objects created underneath. This results in memory leaks, your application performs slow, and you have a big laundry list of items to complain etc etc and etc.

Solution:
3 suggested best practices are as below:

#1. Use Dispose or Close Methods - Technically both are same, just that Dispose again calls Close internally.
#2. Using Clause - Automatic Dispose
#3. Use Try, Catch and Finally Block - Manual Force - Best method as I feel, since it gives you the power of catching the exceptions if any.


Examples:


"using Clause"
 
String str;

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

In the above example though SPSite is the parent of SPWeb and takes care of disposing the SPWeb object (incase you havent auto or forced it), its good to also have the using clause for the SPWeb object too.


"Using Try, Catch and Finally Blocks"
 
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. // NEVER EVER LEAVE THIS BLOCK EMPTY.
}
finally
{
if (oSPWeb != null) // GOOD PRACTICE TO CHECK IF OBJECT IS NOT NULL BEFORE DISPOSING
oSPWeb.Dispose();

if (oSPSite != null) // GOOD PRACTICE TO CHECK IF OBJECT IS NOT NULL BEFORE DISPOSING
oSPSite.Dispose();
}



for more information on Best Practices, follow this link here.

Comments