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 have a code that loops through all the Sites and Webs in a web application. My code uses for..each loop to navigate through each site and web object.

I was wondering if we are required to dispose the SPWeb and SPSite objects when used inside a loop.

Codes:-

foreach (SPSite thisSite in siteAuditWebApplication.Sites) { //My operation here }

Similar to the above code I also have some part of code that loops through all the Web and Lists.

Do we have any best practice for disposing objects inside the loop, or do i really need to take care about disposing the objects?

Thanks in Adv.. Sudhir

share|improve this question

3 Answers 3

up vote 3 down vote accepted

I would strongly recommend you go through this reference article if you haven't done so already http://msdn.microsoft.com/en-us/library/aa973248(v=office.12).aspx#sharepointobjmodel__spwebobjects

share|improve this answer
    
Thanks a lot, I always thought object under for..each will auto dispose. Nice article –  Sudhir Kesharwani Sep 11 '12 at 18:47

Yes you need to dispose of all of them.

foreach (SPSite thisSite in siteAuditWebApplication.Sites) 
{ 
    //My operation here 
    thisSite.Dispose();
}
share|improve this answer
    
Thanks a lot Steve. –  Sudhir Kesharwani Sep 11 '12 at 18:48

If you are worried about disposing all the objects correctly, you can view ULS log and look for the following message

An SPRequest object was not disposed before the end of this thread. To avoid wasting system resources, dispose of this object or its parent (such as an SPSite or SPWeb) as soon as you are done using it.

Having those messages in your ULS logs indicates that some of your code might not call dispose on all disposable SPWeb/SPSite objects.

share|improve this answer
    
Thanks a lot everyone, the suggestions from Steve worked really well and I don't see any messages related to SPRequest object on my ULS log. –  Sudhir Kesharwani Sep 14 '12 at 20:11

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.