Use Close and Finally
In the last 2 weeks I have had two different clients complain that there are "memory leaks" in .NET. I tell them very politely, that most likely it is their code!<g> In both cases it was their code. The first case had to do with the programmers using a DataReader and not closing them when they were done with them, or they put the Close() method call within their Try block and not in a Finally. The second case involved the StreamWriter in the File.IO namespace where once again the file was not always being closed correctly due to the programmer not putting the close in the Finally block. Below is what the original code looked like:
using System.IO;
private void CreateLogFile()
{
try
{
StreamWriter sw =
new StreamWriter(@"D:\Samples\Test.txt",
true, System.Text.UTF8Encoding.UTF8);
sw.WriteLine("This is some text");
sw.Close();
}
catch(Exception ex)
{
throw ex;
}
}
You can see in the above code that the sw.Close() method is within the Try block. If an exception occurs when trying to open or write to the file, the code would go immediately to the Catch block and the Close would never execute. If this method is being called many times, this can cause and "apparent" memory leak. With just a little re-factoring the code was fixed to close the file in the Finally block.
private void CreateLogFile()
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(@"D:\Samples\Test.txt",
true, System.Text.UTF8Encoding.UTF8);
sw.WriteLine("This is some text");
}
finally
{
if (sw != null)
{
sw.Close();
}
}
}
Notice that there are three items that we had to fix up here. First, the declaration of the StreamWriter was moved out of the Try block. If we did not do this, then the variable "sw" would not able to be accessed from within the Finally block since it would have block-level scope only within the Try portion. Secondly, we created a Finally block, checked the "sw" variable for null, and if it was not null then we closed it. Thirdly, since nothing was happening with the catch, we eliminated it all together.
Watch these types of scenarios as this can cause hard-to-find bugs in your code.
Past Blog Content
Blog Archive
-
2015
-
2014 (18)
-
2013 (11)
-
2012 (19)
-
2011 (29)
-
2010 (19)
-
2009 (28)
-
2008 (0)
-
2007 (14)
-
2006 (6)