Do you need to call Flush() on a stream or writer if you are using the “using” statement?

拟墨画扇 提交于 2019-12-17 23:34:02

问题


I am not sure whether I need to call Flush() on the used objects if I write something like this:

using (FileStream...)
using (CryptoStream...)
using (BinaryWriter...)
{
    // do something
}

Are they always automatically flushed? When does the using statement flush them and when it doesn’t (if that can happen)?


回答1:


As soon as you leave the using block’s scope, the stream is closed and disposed. The Close() calls the Flush(), so you should not need to call it manually.




回答2:


It varies, Stream by default does not call Flush() in the Dispose method with a few exceptions such as FileStream. The reason for this is that some stream objects do not need the call to Flush as they do not use a buffer. Some, such as MemoryStream explicitly override the method to ensure that no action is taken (making it a no-op).
This means that if you'd rather not have the extra call in there then you should check if the Stream subclass you're using implements the call in the Dispose method and whether it is necessary or not.

Regardless, it may be a good idea to call it anyway just for readability - similar to how some people call Close() at the end of their using statements:

using (FileStream fS = new FileStream(params))
using (CryptoStream cS = new CryptoStream(params))
using (BinaryWriter bW = new BinaryWriter(params))
{
    doStuff();
    //from here it's just readability/assurance that things are properly flushed.
    bW.Flush();
    bW.Close();
    cS.Flush();
    cS.Close();
    fS.Flush();
    fS.Close();
}


来源:https://stackoverflow.com/questions/7710661/do-you-need-to-call-flush-on-a-stream-or-writer-if-you-are-using-the-using-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!