4

Suppose we have code:

CASE 1:

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
    {
        SPWeb web = site.RootWeb;
    } 

Do we need to dispose the SPWeb in this case?

CASE 2:

 using (SPSite site = new SPSite(SPContext.Current.Web.Url))
        {
            SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb();
        } 

Do we need to dispose the SPWeb in this case? Or does it get automatically disposed after the using block disposes the SPSite object?

2 Answers 2

9

In first case SPWeb web = site.RootWeb; SPWeb does not need to be disposed as SPWeb is retrieved from RootWeb. However, in second case SPWeb needs to be explicitly disposed. Mere disposal of SPSite is not enough. So the code should look like:

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
    using (SPWeb web = site.OpenWeb())
    {

    }
} 

Note: there is no need to create an SPSite object again when opening SPweb as it is already present.

3
  • blogs.technet.com/b/stefan_gossner/archive/2008/12/05/… This articles says: "dispose for the SPSite object in position 1 will automatically dispose all SPWeb objects bound to the SPSite object.", can you check please.
    – variable
    Apr 23, 2014 at 5:17
  • It also mentions "You should dispose a SPWeb or SPSite object after the last access to a child object of this object." This is done by having the using statement. using is equivalent to try catch finally Apr 23, 2014 at 5:25
  • 1
    Just curious, do you know how RootWeb is disposed by SPSite? When decompiling the SharePoint DLL I can't see where it is disposed at all. I think m_openedWebs are all disposed of properly, but RootWeb is not part of these. I know it is disposed, I just can't see where it is done
    – eirikb
    Apr 23, 2014 at 6:10
2

No, we need to dispose the SPWeb object separately. Because we are not assigning current SPWeb context to the web variable.

Here, 1. We are first getting the SPSite object from current context web url 2. Then we are retrieving the SPWeb object from SPSite 3. After that we are assigning that variable to the SPWeb.

So, we need to dispose the SPWeb object separately in Case 2 to clear the garbage memory. In Case 1: SPWeb object (web) is automiatically disposed by site.

2
  • Are you sure that: SPWeb web = site.RootWeb; needs to be disposed?
    – variable
    Apr 23, 2014 at 5:18
  • No need. For Case 1, the web object automatically disposed by site. Apr 23, 2014 at 5:33

Your Answer

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

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