0

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

3 Answers 3

3

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

1
  • Thanks a lot, I always thought object under for..each will auto dispose. Nice article Commented Sep 11, 2012 at 18:47
1

Yes you need to dispose of all of them.

foreach (SPSite thisSite in siteAuditWebApplication.Sites) 
{ 
    //My operation here 
    thisSite.Dispose();
}
0
1

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.

1
  • 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. Commented Sep 14, 2012 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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