0

Do i need to dispose SPSite object here ?

     using (SPWeb web = new SPSite(siteCollectionURL).OpenWeb())
{
//work with web
}

From Microsoft site,

void CombiningCallsLeak()
{
    using (SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb())
    {
        // ... New SPSite will be leaked.
    } // SPWeb object web.Dispose() automatically called.
}

https://msdn.microsoft.com/en-us/library/aa973248(v=office.12).aspx

2

The problem doing it like that is that you have no way of disposing the SPSite object outside of the SPWeb using statement as the SPSite object is encapsulated in the "wrong" using statement.

So in your code example your SPWeb object will be automatically disposed when the code leaves the using statement, but the SPSite object will remain in memory and leak until the GarbageCollector eventually reaches it (which no one knows when is).

Therefore it is much better to have nested using statements like so:

using(SPSite site = new SPSite(<Some site url or site ID>))
{
    using(SPWeb web = site.OpenWeb())
    {
        // Do some magical stuff here
    } // SPWeb object web.Dispose() automatically called.
} // SPSite object site.Dispose() automatically called.

If you insist on only automatically disposing the SPWeb object like in your sample code, at least make a reference to the SPSite object outside of the using statement first so that you can dispose of it properly at a later point

public void SomeMagicalMethod()
{
    SPSite site = new SPSite(<Some site url or site ID>);

    using (SPWeb web = site.OpenWeb())
    {
        // Do your magical stuff with the SPWeb object
    } // SPWeb object web.Dispose() automatically called.

    // Do your magical stuff with your SPSite object
    site.Dispose();
}
1

Yes you need to dispose of SPSite if you code it like that. If you want to use only one using statement and the SPWeb you are looking for is the RootWeb (hinted by the name of your URL variable), you can code it like this.

using (SPSite site = new SPSite(siteCollectionURL))
{
    SPWeb web = site.RootWeb;
    //Work with web
}

You don't need to dispose the RootWeb of an SPSite, it will be automatically disposed when disposing the parent.

0

Just to clarify a using statement is just a try catch finally wrapper. It ensures that the objects are disposed of when an exception occurs.

Also if you early exit from a method it will handle the dispose for you. It's the safest way of preventing memory leaks.

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.