Disposing in SharePoint and an Exception from HRESULT

by

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: , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.