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?

有帮助吗?

解决方案

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();
        }
    }

其他提示

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.

许可以下: CC-BY-SA归因
scroll top