Does disposing streamreader close the stream?(处理 streamreader 会关闭流吗?)
问题描述
我正在向要写入的方法发送流,并且在这些方法中我使用的是二进制读取器/写入器.当读取器/写入器被处理时,无论是通过 using
还是没有被引用,流是否也关闭了??
I am sending a stream to methods to write on, and in those methods I am using a binary reader/wrtier. When the reader/writer gets disposed, either by using
or just when it is not referenced, is the stream closed as well??
我会发送一个 BinaryReader/Writer,但我也在使用 StreamReader(也许我应该解决这个问题.我只将它用于 GetLine 和 ReadLine).如果每次关闭写入器/读取器时它都关闭流,这将非常麻烦.
I would send a BinaryReader/Writer, but I am using a StreamReader too (maybe I should go around that. I am only using that for GetLine and ReadLine). This is quite troublesome if it closes the stream each time a writer/reader gets closed.
推荐答案
Yes, StreamReader
, StreamWriter
, BinaryReader
and BinaryWriter
当您对它们调用 Dispose
时,所有它们都会关闭/处理它们的底层流.如果读取器/写入器只是垃圾收集,它们不会处理流-您应该始终处理读取器/写入器,最好使用 using
语句.(事实上,这些类都没有终结器,也不应该有.)
Yes, StreamReader
, StreamWriter
, BinaryReader
and BinaryWriter
all close/dispose their underlying streams when you call Dispose
on them. They don't dispose of the stream if the reader/writer is just garbage collected though - you should always dispose of the reader/writer, preferrably with a using
statement. (In fact, none of these classes have finalizers, nor should they have.)
就我个人而言,我也更喜欢对流使用 using 语句.您可以非常整齐地嵌套 using
不带大括号的语句:
Personally I prefer to have a using statement for the stream as well. You can nest using
statements without braces quite neatly:
using (Stream stream = ...)
using (StreamReader reader = new StreamReader(stream, Encoding.Whatever))
{
}
即使流的 using
语句有些多余(除非 StreamReader
构造函数抛出异常)我认为这是最佳实践,因为如果你摆脱了StreamReader
并在以后直接使用流,您已经拥有正确的处理语义.
Even though the using
statement for the stream is somewhat redundant (unless the StreamReader
constructor throws an exception) I consider it best practice as then if you get rid of the StreamReader
and just use the stream directly at a later date, you'll already have the right disposal semantics.
这篇关于处理 streamreader 会关闭流吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:处理 streamreader 会关闭流吗?
基础教程推荐
- 创建属性设置器委托 2022-01-01
- 如何使用OpenXML SDK将Excel转换为CSV? 2022-01-01
- 覆盖 Json.Net 中的默认原始类型处理 2022-01-01
- C# - 如何列出发布到 ASPX 页面的变量名称和值 2022-01-01
- Page.OnAppearing 中的 Xamarin.Forms Page.DisplayAlert 2022-01-01
- C# - 将浮点数转换为整数...并根据余数更改整数 2022-01-01
- 从 VB6 迁移到 .NET/.NET Core 的最佳策略或工具 2022-01-01
- 当键值未知时反序列化 JSON 2022-01-01
- 使用 SED 在 XML 标签之间提取值 2022-01-01
- 我什么时候应该使用 GC.SuppressFinalize()? 2022-01-01