如果您使用“using”,是否需要在流或写入器上调用 Flush()陈述?
如果我编写如下内容,我不确定是否需要对已使用的对象调用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一旦离开 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.
情况有所不同,
Stream
默认情况下不会在Dispose
方法中调用Flush()
,但有一些例外,例如FileStream
>。原因是某些流对象不需要调用Flush
,因为它们不使用缓冲区。有些(例如MemoryStream
)显式重写该方法以确保不执行任何操作(使其成为无操作)。这意味着,如果您不想在那里进行额外的调用,那么您应该检查您使用的 Stream 子类是否实现了 Dispose 方法中的调用以及是否有必要还是没有必要。
无论如何,为了可读性而调用它可能是个好主意 - 类似于有些人在 using 语句末尾调用
Close()
的方式:It varies,
Stream
by default does not callFlush()
in theDispose
method with a few exceptions such asFileStream
. The reason for this is that some stream objects do not need the call toFlush
as they do not use a buffer. Some, such asMemoryStream
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 theDispose
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: