Possibility of memory leaks in this code block
-
02-10-2020 - |
Question
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 ?
Solution
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))