Sunday, 9 July 2017

Best Practices: Using SPWeb and SPSite objects in server model.



1. Use dispose method, instead of Close, because SPWeb and SPSite objects implement the IDisposable interface, and standard .NET Framework garbage collection calls the Dispose method to free any resources associated with the object from memory.

2. Add try-finally block within foreach loop to dispose or close the current object.

foreach (SPSite siteCollectionInner in siteCollections)
        {
            try
            {
                // ...
            }
            finally
            {
                if(siteCollectionInner != null)
                    siteCollectionInner.Dispose();
            }
        }

3. Test null before disposing:

finally
{
   if (oSPWeb != null)
     oSPWeb.Dispose();

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

4. Use 'using' with SPSite and SPWeb. This will automatically create a finnaly block to dispose the object.

5. Never use 'using' on objects created/returned by SPContext. Because, SPContext returns managed objects.

6. Bad Coding Practice:

using (SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb())
    {
        // SPSite leaked !
    } // SPWeb object web.Dispose() automatically called.

Good Practice:

using (SPSite siteCollection = new SPSite("http://url"))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
        } // SPWeb object web.Dispose() automatically called.
    }  // SPSite object siteCollection.Dispose() automatically called.

7. In general, any time a calling application uses the new SPSite constructors (any signature), it should call the Dispose() method when it is finished using the object. If the SPSite object is obtained from GetContextSite(), the calling application should not dispose of the object. Because the SPWeb and SPSite objects keep an internal list that is derived in this way, disposing of the object may cause the SharePoint object model to behave unpredictably. Internally, Windows SharePoint Services enumerates over this list after page completion to dispose of the objects properly.

Source: https://msdn.microsoft.com/en-us/library/aa973248.aspx

No comments:

Post a Comment