如果您使用“using”,是否需要在流或写入器上调用 Flush()陈述?

发布于 2024-12-08 21:22:08 字数 238 浏览 1 评论 0原文

如果我编写如下内容,我不确定是否需要对已使用的对象调用 Flush()

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

它们总是自动刷新吗? using 语句何时刷新它们,何时不刷新(如果可能发生)?

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)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吻风 2024-12-15 21:22:09

一旦离开 using 块的作用域,流就会被关闭并释放。 Close() 调用 Flush(),因此您不需要手动调用它。

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.

如梦亦如幻 2024-12-15 21:22:09

情况有所不同,Stream 默认情况下不会在 Dispose 方法中调用 Flush(),但有一些例外,例如 FileStream >。原因是某些流对象不需要调用Flush,因为它们不使用缓冲区。有些(例如 MemoryStream)显式重写该方法以确保不执行任何操作(使其成为无操作)。
这意味着,如果您不想在那里进行额外的调用,那么您应该检查您使用的 Stream 子类是否实现了 Dispose 方法中的调用以及是否有必要还是没有必要。

无论如何,为了可读性而调用它可能是个好主意 - 类似于有些人在 using 语句末尾调用 Close() 的方式:

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();
}

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文