本文介绍了是否Stream.Dispose随时拨打Stream.Close(和Stream.Flush)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下情况:

 的StreamWriter MySW = NULL;
尝试
{
   流MyStream =新的FileStream(asdf.txt);
   MySW =新的StreamWriter(MyStream);
   MySW.Write(嗒嗒);
}
最后
{
   如果(MySW!= NULL)
   {
      MySW.Flush();
      MySW.Close();
      MySW.Dispose();
   }
}
 

我可以只叫 MySW.Dispose()并跳过即使它被设置在关闭?是否有任何流implimentations预期,不工作(就像CryptoStream的)?

如果没有,那么就是下面只是坏code:

 使用(StreamWriter的MySW =新的StreamWriter(MyStream))
{
   MySW.Write(嗒嗒);
}
 

解决方案

是的,这就是它了。

它是安全的假设,如果一个对象实现的IDisposable ,将处置本身正常。

如果没有,那么这将是一个错误。

没有,那code是处理实现的IDisposable

对象的推荐方式

更多优秀的信息是公认的答案关闭和处置 ​​- 这称呼?

If I have the following situation:

StreamWriter MySW = null;
try
{
   Stream MyStream = new FileStream("asdf.txt");
   MySW = new StreamWriter(MyStream);
   MySW.Write("blah");
}
finally
{
   if (MySW != null)
   {
      MySW.Flush();
      MySW.Close();
      MySW.Dispose();
   }
}

Can I just call MySW.Dispose() and skip the Close even though it is provided? Are there any Stream implimentations that don't work as expected (Like CryptoStream)?

If not, then is the following just bad code:

using (StreamWriter MySW = new StreamWriter(MyStream))
{
   MySW.Write("Blah");
}
解决方案

Yes, that’s what it’s for.

It is safe to assume that if an object implements IDisposable, it will dispose of itself properly.

If it doesn’t, then that would be a bug.

No, that code is the recommended way of dealing with objects that implement IDisposable.

More excellent information is in the accepted answer to Close and Dispose - which to call?

这篇关于是否Stream.Dispose随时拨打Stream.Close(和Stream.Flush)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:38
查看更多