简体   繁体   English

StreamWriter何时处置?

[英]When is StreamWriter disposed?

I have a small class I threw together to implement a quick logger. 我有一堂课,我一起来实现一个快速记录器。 I composed it with a private System.IO.StreamWriter which is instantiated in the constructor. 我用在构造函数中实例化的私有System.IO.StreamWriter组成了它。 Because the way I'm using is prevents me from implementing a using block, I added a finalizer and called the StreamWriter's Dispose() method in it. 因为我使用的方式阻止了我实现using块,所以我添加了一个终结器,并在其中调用了StreamWriter的Dispose()方法。 However, when executing, that finalizer throws an exception because the StreamWriter has already been disposed. 但是,在执行时,该终结器将引发异常,因为StreamWriter已被处置。

System.ObjectDisposedException - Cannot access a closed file. System.ObjectDisposedException-无法访问关闭的文件。

I'm confused how this happened and I'm wondering if this means I don't need to worry about cleaning up the StreamWriter. 我很困惑这是怎么发生的,我想知道这是否意味着我不必担心清理StreamWriter。 Here is my class: 这是我的课:

public class TextFileLogger : AbstractTextLogger
{
    private const string LogPath = @"C:\";
    private const string LogFileName = "MyFile.log.txt";
    private readonly StreamWriter _writer;

    public TextFileLogger()
    {
        _writer = new StreamWriter($"{LogPath}{LogFileName}", true);
        _writer.AutoFlush = true;
    }

    ~TextFileLogger()
    {
        _writer.Dispose();
    }

    protected override void WriteLine(string line)
    {
        _writer.WriteLine(line);
    }
}

The only things you are allowed to access in a finalizer are objects that are rooted (like static variables) or objects that derive from CriticalFinalizerObject. 在终结器中,唯一允许访问的是生根的对象(如静态变量)或从CriticalFinalizerObject派生的对象。

The problem is the finalizer is not deterministic, it is allowed to run in any order it feels like. 问题是终结器不是确定性的,允许以其感觉中的任何顺序运行。 The problem you ran in to is because the text writer was finalized before your class. 您遇到的问题是因为文本编写器在上课之前已完成。

You need to either just "hope for the best" and let the writer's finalizer to do the work or you need to refactor your code so your class is disposeable itself and that calls the stream writer's dispose method. 您需要只是“希望最好”,然后让编写器的终结器完成工作,或者您需要重构代码,以便您的类本身是可处置的,并调用流编写器的dispose方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM