是否处理的StreamReader关闭流? [英] Does disposing streamreader close the stream?

查看:919
本文介绍了是否处理的StreamReader关闭流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发送一个流的方法来写,并在这些方法我使用的是二进制读/ wrtier。当读/写器得到处理,或者通过使用或只是当它没有被引用,是流闭以及??

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 /作家,但我使用一个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.

推荐答案

的StreamReader 的StreamWriter BinaryReader 的BinaryWriter 全部关闭/处置其底层流当你调用的Dispose 他们。他们的的处分流,如果读/写器只是收集垃圾,但 - 你应该总是处置读/写器,$ P $的pferrably一个使用语句。 (事实上​​,没有这些类都有终结,也不应该有。)

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

我个人preFER有一个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))
{
}

尽管视频流的使用语句是有些多余的(除非的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关闭流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆