5

I have an issue in my SharePoint environment and I suspect that this code causes a memory leak. I'm passing a SPWeb object as a value parameter.

Will the SPWeb object instance get disposed correctly using this code?

public void DoSomething(SPWeb web)
{
    // code here
}
public void mainProgram()
{
    using (SPWeb web = site.OpenWeb())
    {
        DoSomething(web);
        //another code here
    }
}

2 Answers 2

2

When you pass an object to a method by value, in the method you get simply copy of reference to the same object. No new objects is created, this mean that your code is correct. We need to dispose such object as spweb and spsite because they are using external resources (that require memory), and this resources not destroyed by garbage collector, we had to explicitly call method to remove it and free memory.
When you stop using your web object (right after "}") external resource for this particular object will be free, that's why all is correct.
You can try to verify your code using SPDisposeCheck tool. From my practice when you are using SPLimitedWebPartManager you need to explicitly dispose internal web webPartManaber.Web.Dispose(); (that is not so obvious at a first glance)

2
  • 2
    If you use the SPDisposeCheck tool to check your code, be aware that in some case it will report false positives when an instance is getting disposed outside the scope of the current method (most time, it will warn you that the instance may be disposed by the caller). The above answer still stands right, with your current code the SPWeb instance passed as a parameter will be correctly disposed even if the SPDisposeCheck tool may complain otherwise.
    – SPArcheon
    Dec 23, 2011 at 13:34
  • 1
    The general rule for .Net is that you must explicitly release any resources you create that implement the IDisposable interface; that is, that have a Dispose() method. If you are curious about an object, check to see if it has a Dispose() method. If it does and you created the object, then it is up to you to destroy it. SharePoint can be a little tricky in this regard because it does have methods that create objects when called where it is not immediately clear that they must be managed.
    – Dave Wise
    Dec 23, 2011 at 16:17
6

That code will dispose the SPWeb object correctly with the using statement. If an exception is thrown in the method, it will still get disposed.

1
  • Correct, because of the simple fact that objects are passed by reference by default in C#, thus the SPWeb within the DoSomething method points to the same SPWeb as created in mainProgram. Therefore its sufficient to dispose it in mainProgram only. Oct 17, 2012 at 12:01

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.