Using keyword and Managed\UnManaged code
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,
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
我认为这更像是一种防御性编码风格,我不希望使用流读取器对象,因为与此对象关联的文件已使用ReadtoEnd函数完全读取,并且正在被txt引用。
链接地址: http://www.djcxy.com/p/54510.html