-1

C# keyword Using implements Idisposable which provides a mechanism for releasing unmanaged resources.

Now i was going through this code

string txt = String.Empty;
      using (StreamReader sr = new StreamReader(filename)) {
         txt = sr.ReadToEnd();
      }

and cant stop wondering, why is the keyword Using is used in this code while StreamReader is a Managed resource and it is the responsibility of the garbage collector to free up the objects memory after its scope gets over.

So my question is,

  1. Is the above code simply an explicit way of handling to free up resources
  2. As per my understanding any methods or classes which we use under the .net framework is a managed code, then is not StreamReader also falls under managed code.
  3. Am i missing something on the Managed\Unmanaged code
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
Lijin Durairaj
  • 4,910
  • 15
  • 52
  • 85
  • 3
    the ``StreamReader`` possibly be using in it's implementation some unmanaged resources, so it will make sure they are disposed when wrapped inside using – Ehsan Sajjad Dec 05 '16 at 15:41
  • 1
    .. so in the example you provided, this would be the file handle used to open the file for reading. – stuartd Dec 05 '16 at 15:42
  • 6
    File I/O is an operating system specific service, In Windows a handle approach is used, handles need closing. – Alex K. Dec 05 '16 at 15:43
  • Surely whatever source you're quoting from provided more information than just that one sentence (if it did not, you could no doubt have looked for others). There's no shortage of information on this topic out there. – Servy Dec 05 '16 at 15:43
  • @EhsanSajjad Sajjad will not disposing the StreamReader object clears up the memory and so the unmanaged code also gets cleared? can you give me a little more details on the working – Lijin Durairaj Dec 05 '16 at 15:44
  • 1
    See the `StreamReader.Dispose(Boolean)` Description: Closes the underlying stream, releases the unmanaged resources used by the StreamReader, and optionally releases the managed resources.(Overrides TextReader.Dispose(Boolean).) – James C. Taylor IV Dec 05 '16 at 15:45
  • @JamesC.TaylorIV has given the reference, you can look in details of that method on MSDN – Ehsan Sajjad Dec 05 '16 at 15:46

2 Answers2

1

why is the keyword Using is used in this code while StreamReader is a Managed resource

While StreamReader is a managed object it may hold objects inside it which are not allocated on the managed heap. Garbage Collector has no visibility on their allocation and hence cannot clean them up. For the particular case of StreamReader it internally creates a FileStream (for your particular case) which internally creates and holds a WIN32 filehandle.

_handle = Win32Native.SafeCreateFile(tempPath, fAccess, share, secAttrs, mode, flagsAndAttributes, IntPtr.Zero);

(Code Reference)

using is just shorthand for:

try
{
   var streamReader = new StreamReader(path);
   // code
} 
finally
{
  streamReader.Dispose();
}

Methods implementing IDisposable need to implement Dispose where they get the opportunity to close file handles, sockets, or any such resource that may need manual cleaning.

If one choses to hold a StreamReader inside a class then that class should implement IDisposable too, to correctly pass on the Dispose to the StreamReader.

So the IDisposable can be considered as a contract for classes that either hold native objects, or hold objects that implement IDisposable

bashrc
  • 4,725
  • 1
  • 22
  • 49
-5

I think this is more of a defensive coding style where I don't want the stream reader object to be used as the file associated with this object has already been read completely using ReadtoEnd function and is being referred by txt.

AnshuBhola
  • 206
  • 2
  • 4
  • This is untrue. `using` exists to ensure guaranteed (or at least as close to it as is possible) and prompt cleanup of unmanaged resources. It is not *just* a scoping mechanism. – Servy Dec 05 '16 at 15:53
  • The request to read the file has been fulfilled by an operating system API, this API requires notification when I/O is complete to free associated resources. If something implements IDisposable, dispose it, always. – Alex K. Dec 05 '16 at 15:53