0

I have a tool using a similar code block as follows.

private void createDiscussions()
{                        
   SPWeb newCommunitySite = null;

   try
   {    

     using (SPSite site = new SPSite(siteURL))
     {
      .
      .
      .
      newCommunitySite = site.OpenWeb();    
      .
      .
      .
     }
      newCommunitySite.Dispose();
   }
   catch()
   {
    .
    .
    .
   }
   finally
   {
    newCommunitySite.Dispose();
   }
}

Can this code cause memory leaks ?

Although the code looks nicely wrapped in the Using and try-catch blocks, I have the doubt because the SPWeb object was declared outside of Using and try-catch blocks. Will that be disposed properly(without causing leaks) in all scenarios ?

2
  • At compile time, your SPSite with the using statement to is rewritten as an try finally. It will also declare the variable outside the try, and it handles the IDisposable in the finally. So nothing wrong with declaring it outside the try. Commented Mar 19, 2015 at 6:26
  • Nice to know that Anders...
    – Amit Tyagi
    Commented Mar 19, 2015 at 16:46

1 Answer 1

4

Even though SPWeb is declared outside of try catch block, it is initialized inside try block. And it is disposed inside try and finally blocks. So there won't be any memory leak. Only issue I see in the code is that in the finally block, there should be a null check before an attempt is made to Dispose SPWeb object.

   finally
   {
    if (newCommunitySite != null)
    newCommunitySite.Dispose();
   }

The reason for this is the below line may throw exception for several reasons:

using (SPSite site = new SPSite(siteURL))
2
  • Great explanation. So, do you mean that, if i don't use if (newCommunitySite != null) before disposing the SPWeb object, the code may throw an exception again in the finally block ?
    – Amit Tyagi
    Commented Mar 19, 2015 at 16:45
  • Yes, that is right. Commented Mar 19, 2015 at 16:56

Your Answer

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

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