When working with SharePoint WebParts or Application Pages, following the disposal guidelines is important to ensure the pages are working at top speed and memory efficiency. The most common object to get and dispose is the SPSite object. There are two basic ways to access such an object:
1. By direct addressing:
SPSite site = new SPSite("http://www.contoso.com/");
When using this approach, the SPSite object should be disposed by invoking the Dispose() method:
site.Dispose();
An even better way to dispose objects when they are no longer needed is the Using (..) statement, which automatically disposes objects at the end of the code it’s enclosing:
using (SPSite site = new SPSite("http://www.contoso.com/"))
{
// do something with the site object..
}
2. By using SPContext
Another method of acquiring the SPSite object is this:
SPSite site = SPContext.Current.Site
This object is using the already opened site object of the current SharePoint context and does not need to be disposed. In fact, I would like to add a third method..
3. How NOT to do it
Don’t overdo it by using the following code:
using (SPSite site = SPContext.Current.Site)
{
// Do something here
}With this code, you will dispose the site object of the current site, while it is being constructed. This will lead to the following exception:
Exception from HRESULT: 0×80131904
This exception occurs if an erroneous WebPart is used on a WebPart page. It will be displayed any time a user tries to move or remove a WebPart from a WebPart zone or change the settings of any WebPart on the page. To remove or prevent the error check your WebParts with SPDispose and correct the disposal errors.
Tags: best practice, code, disposing, example, exception, tutorial