本文介绍了什么情况下可以不关闭的StreamReader / StreamWriter的保持底层流打开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,基本上包装了一个流的读/写,但流预计将在该类的消费者进行管理。为了方便使用,我使用的StreamReader和StreamWriter类的流进行I / O操作。一般情况下我在包装使用块的读写器,但我想避免关闭读写器,因为这样做也关闭底层流,我必须保持打开。

I have a class that essentially wraps a Stream for reading/writing, but that stream is expected to be managed by the consumer of that class. For ease of use, I use StreamReader and StreamWriter classes to perform I/O operations on the stream. Normally I'd wrap the reader and writer in using blocks, but I want to avoid closing the reader and writer because doing so also closes the underlying stream and I have to keep it open.

时在内存/资源管理方面的安全无法关闭一个StreamReader / StreamWriter的,如果我希望底层流被调用者进行管理?将读写器收集垃圾时,流明确别处关闭?

Is it safe in terms of memory/resource management to not close a StreamReader/StreamWriter if I expect the underlying Stream to be managed by the caller? Will the reader and writer be garbage collected when the stream is explicitly closed elsewhere?

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
    }
}


推荐答案

如果没有人关闭了流,那么最终的终结将被调用这应该叫处置和关闭它们在GC。但是,这是一个相当扯淡射击资源明智的,原因是其离开的任何可能,昂贵的资源分配,直到GC。它可能变得更糟的时间越长你的对象的生活,尤其是如果它生存的集合晋升为第一代,甚至2

If nobody closes the streams then ultimately the finalizer will be called which should call dispose and close them upon GC. But that's quite a crap-shoot resource-wise becuase it leaves whatever possibly-expensive resources allocated until GC. It could get worse the longer your object lives, especially if it survives collections to be promoted to gen 1 or even 2.

这肯定将是很好,如果你能提出一些您调用者隔离这一点。 ?也许你可以缓存从流的东西,所以你可以关闭它,同时仍然提供内容给主叫方

It sure would be nice if you could present something to your caller that isolates this. Perhaps you can cache something from the stream so you can close it while still serving the content to your caller?

修改您的修改后:现在我看到你的调用者传递你流进行操作,我的回答必须是不同的!这是非常清楚的,你方应负责管理该流的寿命。我在第一次您的类创建流并希望呼叫者管理它的印象。

EDIT after your edit: Now that I see your caller PASSES you a stream to operate on, my answer has to be different! It's very clear that your caller should be managing the stream's lifetime. I had the impression at first that your class created a stream and hoped the caller managed it.

这篇关于什么情况下可以不关闭的StreamReader / StreamWriter的保持底层流打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 14:12