我有一个类基本上包装流读取/写入,但该流预计由该类的消费者管理。为了便于使用,我使用StreamReader和StreamWriter类对流进行I/O操作。通常情况下,我会将读写器封装在using
块中,但我想避免关闭读写器,因为这样做也会关闭底层流,并且必须保持打开状态。是否可以不关闭StreamReader/StreamWriter以保持底层流的打开?
是在内存/资源管理等方面的安全,不能关上一个StreamReader/StreamWriter的,如果我希望底层流被调用者进行管理?当流在其他地方显式关闭时,读者和作者是否会被垃圾收集?
public class Wrapper
{
private Stream _underlyingStream;
public Wrapper(Stream underlyingStream)
{
_underlyingStream = underlyingStream;
}
public string GetValue()
{
_underlyingStream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(_underlyingStream);
return reader.ReadToEnd(); // we're done, but the stream is not ours to close
}
}
这个问题可能会有所帮助:http://stackoverflow.com /问题/ 1862261 /可任您保持-A-的StreamReader - 从配置用最底层的流 – 2010-12-16 22:09:44
不相关的问题,但因为包装不“拥有”流,你可能想也节省了原始'_underlyingStream.Position'并在返回给调用者之前将其恢复到ReadToEnd()之后的那个位置。 (虽然,您的使用可能会使呼叫者期望此位置受到此类呼叫的影响 - 并且如果它很重要,可以自行保存位置。) – 2016-03-22 22:49:16