Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I'm trying to understanding the object clean up process.

using (SPSite siteCollection = new SPSite(siteUrl))
{
  SPWeb site = siteCollection.RootWeb;
  foreach (SPList list in site.Lists)
  {
     if (!list.Hidden)
     {
       Console.WriteLine(list.Title);
     }
  }
}

Do I need to wrap a second using against the SPWeb object in the code above?

I've read somewhere that this is not needed because wrapping a using around the SPSite will clean up any child web.

share|improve this question
    
I would recommend to use the SP Dispose Checker Tool that can help to find dispose issues. It's not magic bullet, but it can help to avoid some common mistakes. –  Steve B Jun 27 '12 at 15:04

1 Answer 1

up vote 5 down vote accepted

Both SPSite and SPWeb objects implement the IDisposable interface. When the SPSite object finally gets disposed it will loop through the list and ensure that all SPWeb objects associated with this SPSite object also get disposed.

This might lead to the assumption that just disposing all SPSite objects rather than disposing each individual SPWeb object would be sufficient to minimize the memory usage. In theory this is correct. But it will postpone the dispose of the SPWeb object to the time when the SPSite object gets disposed. So the dispose does not happen right after the SPWeb object is no longer used but much later.

Therefore, SPSite and SPWeb objects should be disposed in the same method they get allocated. That's the best method to ensure that no disposed can be missed and to ensure that a dispose does not occur for an object that will be used later.

Reference: http://blogs.technet.com/b/stefan_gossner/archive/2008/12/05/disposing-spweb-and-spsite-objects.aspx

Regarding your code: You can use using statement or finally block to Dispose the SPWeb object.

share|improve this answer
    
Thanks this makes sense. So it will eventually clean up in the end when SPSite is disposed but just postpone until this time. I see the danger there now cheers. –  TheLazyChap Jun 28 '12 at 2:27
1  
Here is another good reference for 2010: msdn.microsoft.com/en-us/library/ee557362.aspx –  Mike Oryszak Jun 28 '12 at 13:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.