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.


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


I would strongly recommend you go through this reference article if you haven't done so already.

|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 
|improve this answer|||||

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.

|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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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