Coding Practice: Handling Streams

Coding Practice: How do I prevent memory leaks when working with streams?
The safest practice is to leverage a “using” block whenever you work with streams.  The most dangerous practice is to create a stream as a static member of your class, since this creates a type of memory leak since streams are an unmanaged resource in .NET.

Quote:
“Simply calling Dispose() on an object is not enough. The using keyword will prevent resource leaks even in the presence of an exception.”
– Daniel Turini

Application:
In practice, whenever you see a   stream, it should be surround in a “using” block as follows:

try
{
   using (StreamReader sr = new StreamReader(FileName))
   {
      return sr.ReadToEnd();
   }
}
finally
{
   File.Delete(FileName);
}

References:
http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET

About Chris VanHoose

Principal Software Architect at CT Lien Solutions
This entry was posted in Software Architecture and tagged , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.