-1

I have slight memory leak in my app and I was wondering what is best practise when when I am finished processing a FileStream and Streamreader.

here is my code:

using (var stream = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(stream))
{
    //do what I need with the file

     sr.Close();
     stream.Close();  
 }

Should I be called Dispose on the stream object and StreamReader Object instead? Or is closing both here good enough?

Thanks

Andrew Burns
  • 346
  • 4
  • 15
  • Are you sure the memory leak is present in the code you posted, have you done profiling using Visual Studio profiling tools ?, You don't need to explicitly call Dispose and Close methods when you are using a using statement, check this post about it http://stackoverflow.com/questions/11968289/memorystream-in-using-statement-do-i-need-to-call-close – Abdul Mateen Mohammed Sep 10 '16 at 06:54
  • I Originally thought my memory leak was caused by the FileSystemWatcher which apparently has a memory leak issue in .Net 4. I upgrade to 4.5 but memory leak still occurs. This is really the only other part of my app. – Andrew Burns Sep 10 '16 at 06:57
  • Andrew Burns, please try to run memory diagnosis in Visual Studio to find the exact lines of code where the memory leaks are occurring check these links https://blogs.msdn.microsoft.com/visualstudioalm/2014/04/02/diagnosing-memory-issues-with-the-new-memory-usage-tool-in-visual-studio/ https://www.youtube.com/watch?v=lU_YZtvslnI https://dzone.com/articles/profiling-application-visual-1 – Abdul Mateen Mohammed Sep 10 '16 at 07:07

1 Answers1

2

You don't need to call Close() or Dispose() at all since you've wrapped your streams in a using block.

The using block will automatically dispose the streams for you when you reach the end of the block.

Your memory leak most likely resides elsewhere.

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75