views:

70

answers:

3

Hello,

In the following code example,will filestream and streamreader get disposed or will they create memory leaks? Is it possible to code this function without causing memory leaks?

  string ReadFile(string strPath)
     {
         using (FileStream fstream = new FileStream(strPath, FileMode.Open))
         {
             using (StreamReader sreader = new StreamReader(fstream))
             {
                return sreader.ReadToEnd().ToString(); //NOTE ITS RETURNED HERE...SO CAN IT GET DISPOSED AFTER THIS LINE?
             }
         }
     }

Thanks

+5  A: 

using directive means:

try
{
var iDisposable = new IDisposable();
//using iDisposable...
}
finally
{
//here IDisposable's dispose
}

So yes both fstream and sreader will be disposed.

Eugene Cheverda
but the objects get returned even before dispose is called right?
Josh
Yes, the final string object that resulted from all the operations (the function return value) is fine, even after the objects that generated it get disposed.
Bruce
The objects will be returned and then finally block will be called where defined IDisposable, FileStream for example, will be disposed.
Eugene Cheverda
Call order will be : function call, FileStream.ctor, StreamReader.ctor, StreamReader.ReadToEnd, String.ToString, StreamReader.Dispose, FileStream.Dispose, End of function
VirtualBlackFox
A: 

GC.Collect() may helps you..

http://dotnetperls.com/gc-collect

http://msdn.microsoft.com/en-us/library/xe0c2357.aspx

Judas Imam
Is it really necessary to call GC.Collect after a using statement? He does not want to set these resources free instantaneously but hes not sure if they get collected at all (which they are, when the GC decides to do so).
atamanroman
From the very first article you posted: "So when should you call the GC.Collect method in your .NET programs? In my experience, the answer is basically never [...] in deployment, the GC.Collect method is not useful because it often has little benefit and might even reduce performance, while increasing complexity and causing you headaches."
fencliff
Unmanaged resources are freed immediately when Dispose is called in this case. As for managed resources, except in special cases like before big continuous allocations you shouldn't mess with the GC
VirtualBlackFox
A: 

The using directive calls the Dispose() method regardless whether the instantiating method returns within the block or not.

Please note, however, that you could use the System.IO.File.ReadAllText method to achieve the same with less code:

 string ReadFile(string strPath)
 {
     return System.IO.File.ReadAllText(strPath);
 }
fencliff
yes,I'm aware of this,but I need to repeatedly access the file to store and read data
Josh