Monday, November 10, 2008

Release the memory after using a SPWeb object

It is important to clean up after you are done with a SPWeb. Below is a snippet of code that connects to the top level site of SharePoint and loops through all the webs (recursively). The important thing to note here is that after we do whatever we want to do with the web, we call the Dispose() method on the SPWeb. If you don't do this and your site if big, you will run out of memory. Since this code needs to run on your SharePoint server, it is definitely not a good thing to use up all your memory. :)

using (SPSite site = new SPSite("http://sharepointserver"))
{

   SPWebCollection webs = site.AllWebs;
   foreach (SPWeb web in webs)
   {
       DoSomethingWithWeb(web);
       web.Dispose();
   }
}

No comments: