Monday, May 26, 2014

Using disposable Objects in SharePoint

Its always best practice to use the "using" statement to create the SPSite and SPWeb (IDisposable) object.
So "using" statement will call the Dispose method in correct way for you. Not only that, Using operator ensures the Dispose methods has been called even exception occurred in the using statement block.

Despite SPSite and SPWeb objects are created as managed object majority of the object uses the unmanaged code and  memory to query the SQL table data.

If simply said, every SPSite and SPWeb object call the SQL related classes those are unmanaged code.

So mismanaged of the SPSite and SPWeb object leads to unnecessary application pool recycles,application crashes and high memory usage on all web front ends.

Best approach

 using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                using (SPWeb web = site.OpenWeb()) //root site,if you work on the specific web you can use
                 //site.AllWebs["Child site's relative url"]


* here I using only the Url property of the current site from the SPContext not object.

You should not use the SPContext object for creating the new SPSite or SPWeb object to be used in the Using statement block when you trying to retrieve the site data inside the using statement block.
Because using statement will call the dispose method and it will throw the error like

Getting a error: Attempted to use an object that has ceased to exist. (Exception from HRESULT: 0x80030102 (STG_E_REVERTED))

Bad approach #1

          using (SPSite site = SPContext.Current.Site)
                using (SPWeb web = SPContext.Current.Web) // or SPWeb web = site.OpenWeb()

Bad approach #2
SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web

But you use approach # 2 with try,catch and finally with proper