Dispose of SharePoint SPSite

The script that I have is in the Execute method for SPJobDefinition, which I want to go through every SPSite in the web application. So I have the following code:

foreach (SPSite site in this.WebApplication.Sites) { ... } 

The question is, do I need to manage each site? The rule that I usually go through is laid out or placed inside use only if I update it myself. Will this property of objects actually contain fully constructed site objects, from which I will refer only in this code. If so, deleting the sites will be dangerous, as I am modifying another object that might want them. Or vice versa, the Sites property creates objects on demand .. In this case, is it my responsibility to delete them?

Plus, how do I handle if I need it. I canโ€™t use use in this case, and will it cause hold inside the foreach, iterating over the enumeration?

+4
source share
3 answers

Yes Yes. See โ€œWriting applications scalable for a large number of usersโ€ in Recommendation: General coding problems when using the SharePoint object model . The correct template is:

 foreach (SPSite site in this.WebApplication.Sites) { try { ... } finally { site.Dispose(); } } 

A call to dispose will not interrupt the enumeration. It just cleans up the unmanaged memory used by the object.

+15
source

The manual is here http://www.sharepointdevwiki.com/display/public/When+to+Dispose+SharePoint+objects

suggests that

 //loop through each sub site for (int i = 0; i <= rootweb.Webs.Count; i++) { using (SPWeb subweb = rootweb.Webs[i]) { //do stuff } } 

is the preferred solution to this problem.

There is also a tool that you can run on your solution to verify that you are doing everything right. http://code.msdn.microsoft.com/SPDisposeCheck

0
source

Source: https://habr.com/ru/post/1286361/


All Articles