Up until this point, I've been whipping up demos for my readers to show you how to get started. Well, I was recently called out by a colleague about some of the code that I've written in my posts. (I haven't always been disposing my objects.) From now on, I will try to do things the correct way for your benefit.
Rule of thumb. If there is a Dispose() method in your object, USE IT. Since SPSite and SPWeb are the most used objects, you'll need to make sure you dispose of these objects when you're done with them.
"But won't the garbage collector deal with them?"
Yes, but not quickly. SPSite and SPWeb both have references to the SPRequest object which heavily relies on unmanaged code that is used to read/write to the content database.
Sometimes, you may forget to dispose of your objects (like I have on this site a few times). So, what should you do to make sure you don't forget.
Get used to working with Using statements. A Using statement will automatically dispose of your objects as soon as your code falls out of the block.
An example of this would be:
using (SPSite site = new SPSite("http://local"))
{
using (SPWeb web = site.OpenWeb())
{
//your code here
}
}
MSDN has a good article on Best Practices using disposable SharePoint objects. You should definately take a look at the article.Labels: Developer