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 会关闭流吗?


基础教程推荐
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 从 C# 控制相机设备 2022-01-01