问题描述
大家好!
我对C#中的使用"块进行资源清理有一些疑问...
我正在阅读C#书籍,每个作者都提供了有关使用"的示例:
Hi everyone!
I have some question about "using" block in C# for resource cleanup...
I''m reading C# books and each author gives examples on "using":
using (StreamWriter sw = new StreamWriter(@"C:\sample.txt") )
{
sw.WriteLine("some info");
sw.WriteLine("blah - blah");|
}
就这样...他们没有使用sw.Close()方法!!!!!!!!!!!!!!!!!!!!!!!!!
我知道在使用"语句中,即使发生异常,evrything也是已处置....
但无论如何,必须有一种方法来关闭流,以便可以例如在文件末尾添加EOF符号或其他内容........
在使用"块中会发生以下情况:
That''s it ... they didn''t use sw.Close() method !!!!!!!!!!!!!!!!!!!!!!!!!
I know that in "using" statement evrything is Disposed, even if exceptions occur....
but anyway there must be a mean to close a stream so it could, for example, add EOF symbols to the end of the file or something ........
in "using" block such happens:
finally
{
if ( sw != null)
((IDisposable)sw).Dispose();
}
因此,它将"sw"对象放置到处置队列,以便GarbageCollector稍后将其删除.....
这样所有的时间程序都可以访问我的物理驱动器.........
我不希望...如果其他对象发生其他一些异常怎么办,那么它就不会处理我的"sw"对象,导致程序被中断......
...即使正常放置"sw"对象....也会关闭它?? ..是否会添加EOF符号以标记文件的结尾??
请解释....
So it places "sw" object to the dispose queue so GarbageCollector will delete it later.....
so all that time program would have access to my physical drive .........
I don''t want that ... what if some other exceptions from other objects occur so then it would not dispose my "sw" object cause the program would be interrupted......
...And even if it normally disposes "sw" object ....will it close it ??.......will it add EOF symbol to mark the end of file????
Please explain.....
推荐答案
protected override void Dispose(bool disposing)
{
try
{
if ((this.stream != null) && (disposing || (!this.Closable && (this.stream is __ConsoleStream))))
{
this.Flush(true, true);
if (this.mdaHelper != null)
{
GC.SuppressFinalize(this.mdaHelper);
}
}
}
finally
{
if (this.Closable && (this.stream != null))
{
try
{
if (disposing)
{
this.stream.Close();
}
}
finally
{
this.stream = null;
this.byteBuffer = null;
this.charBuffer = null;
this.encoding = null;
this.encoder = null;
this.charLen = 0;
base.Dispose(disposing);
}
}
}
}
请注意对Flush()和Close()的调用
Notice the calls to Flush() and Close()
这篇关于如何正常关闭流???的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!