Dispose the correct SPSite object for garbage collection
-
09-10-2020 - |
Question
I have these lines of code:
string siteUrl = "http://myTestSite";
using (SPSite siteCollectionParent = new SPSite(strUrl))
{
SPWebApplication webApplication = siteCollectionParent.WebApplication;
SPSiteCollection childCollections = webApp.Sites;
foreach(SPSite siteCollectionChild in childCollections)
{
try
{
System.Console.Writeline(siteCollectionChild.Url);
}
finally
{
//Add here some code
}
}
}
I want to dispose the SPSite object. Which is the best solution to dispose it? Adding siteCollectionChild.Dispose()
, adding childCollections.Dispose()
or siteCollectionParent
is disposed by garbage collection?
La solution
If you write:
using (SPSite siteCollectionParent = new SPSite(strUrl))
you don't need to dispose because the using-Method will do this for you as you guessed. But this has no impact on your child-Instances! So for disposing your siteCollectionChild you can write
foreach(SPSite siteCollectionChild in childCollections)
{
try
{
System.Console.Writeline(siteCollectionChild.Url);
}
finally
{
siteCollectionChild.Dispose();
}
}
Autres conseils
If you dispose SPSite siteCollectionParent
it will dispose only site collection with url strUrl
. ie. only 1 site collection
And disposing childCollections
or every single siteCollectionChild
is similar. just you are disposing in a go if you dispose childCollections
.
NOTE: You are disposinig every single SPSite in the web application.
Be careful about requirement and decide which one you want to dispose.