如何从流阅读器或流作者分离流?

时间:2021-04-06 23:12:04

I have a class which accepts a stream as input (in the constructor). It surfaces content from this stream through various methods.

我有一个类,它接受流作为输入(在构造函数中)。它通过各种方法从流中显示内容。

However, I don't want my object to be responsible for closing the stream -- that should be the responsibility of the caller. I therefore need to close my StreamReader inside my class, but I can't close the underlying stream.

但是,我不希望我的对象负责关闭流——这应该是调用者的责任。因此,我需要在类中关闭StreamReader,但无法关闭底层流。

Is this possible?

这是可能的吗?

2 个解决方案

#1


3  

StreamReaders are designed to take complete and sole ownership of the underlying stream.

流阅读器的设计目的是获得底层流的完整和唯一所有权。

In particular, the StreamReader will arbitrarily read ahead in the stream to fill an internal buffer. (This bit me once)

特别是,StreamReader将在流中任意提前读取,以填充内部缓冲区。(这一点我一次)

If you need to share the stream, you probably shouldn't use a StreamReader at all.

如果您需要共享流,那么您可能根本不应该使用StreamReader。

#2


4  

Closing the streamreader will close the underlying stream. There is no way around that. However, the only reason you need to close a streamreader is so that the underlying stream is also closed. The rest of it is all managed code. That means you can just abandon your streamreader and everything should be fine — assuming your caller remembers to close their stream as they should.

关闭streamreader将关闭底层流。这是不可能的。然而,您需要关闭一个streamreader的惟一原因是使底层流也被关闭。其余的都是托管代码。这意味着你可以放弃你的streamreader,一切都很好——假设你的调用者记得关闭他们应该关闭的流。

#1


3  

StreamReaders are designed to take complete and sole ownership of the underlying stream.

流阅读器的设计目的是获得底层流的完整和唯一所有权。

In particular, the StreamReader will arbitrarily read ahead in the stream to fill an internal buffer. (This bit me once)

特别是,StreamReader将在流中任意提前读取,以填充内部缓冲区。(这一点我一次)

If you need to share the stream, you probably shouldn't use a StreamReader at all.

如果您需要共享流,那么您可能根本不应该使用StreamReader。

#2


4  

Closing the streamreader will close the underlying stream. There is no way around that. However, the only reason you need to close a streamreader is so that the underlying stream is also closed. The rest of it is all managed code. That means you can just abandon your streamreader and everything should be fine — assuming your caller remembers to close their stream as they should.

关闭streamreader将关闭底层流。这是不可能的。然而,您需要关闭一个streamreader的惟一原因是使底层流也被关闭。其余的都是托管代码。这意味着你可以放弃你的streamreader,一切都很好——假设你的调用者记得关闭他们应该关闭的流。