是否处理的StreamReader关闭流? [英] Does disposing streamreader close the stream?
问题描述
我发送一个流的方法来写,并在这些方法我使用的是二进制读/ 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屋!