处理 streamreader 会关闭流吗?
- 作者: 丁坤演的好
- 来源: 51数据库
- 2022-12-15
问题描述
我正在向要写入的方法发送流,并且在这些方法中我使用的是二进制读取器/写入器.当读取器/写入器被处理时,无论是通过 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.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
