Make use of “using” when dealing with the SPWeb object

Whenever you need to create an SPWeb object it is highly recommended that you dispose explicitly once you do not need it any longer. This can be done using the “using”-construct. Typically this works as follows:

using(SPWeb web = new SPSite("http://localhost").OpenWeb())
{
    // your code here
}

The reason for this is that the SPWeb object is especially large so that when a lot of users call your custom code in the context of SharePoint a lot of memory is allocated and never freed again (memory leak). The Internet Information Service (IIS) reacts by recycling the corresponding application pool. When this happens the next user coming across any of your application pages will wait quite some time, as the application needs to be re-initialised. If this happens a lot then your users will complain about performance issues. The problem of course is that you cannot reproduce this reliably so developers will have a hard time pin-pointing the problem.

This msdn entrye on this subject is worth reading.

Advertisements

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: