是否Stream.Dispose随时拨打Stream.Close(和Stream.Flush)Dispose、Stream、Flush、Close

2023-09-02 21:08:18 作者:没心没肺く小男人

如果我有以下情况:

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

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

Media Stream官方下载2019 Media Stream网页版

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

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

解决方案   

我可以只调用MySW.Dispose()和   跳过关闭,即使它是   提供?

是的,这就是它了。

  

有没有流实现   预期不工作(像   CryptoStream的)?

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

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

  

如果不是,则在下面的只是坏   code:

没有,那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");
}

解决方案

Can I just call MySW.Dispose() and skip the Close even though it is provided?

Yes, that’s what it’s for.

Are there any Stream implementations that don't work as expected (Like CryptoStream)?

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.

If not, then is the following just bad code:

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?