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