自关闭StreamWriter单例 [英] Self-closing StreamWriter singleton

查看:83
本文介绍了自关闭StreamWriter单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在位于以下网址的刷新StreamWriter中进一步缩小问题的范围: 实现了类似单例的自关闭 StreamWriter

I tried to further narrow down the problem in Flush StreamWriter at the end of its lifetime implementing a singleton-like self-closing StreamWriter:

class Foo : System.IO.StreamWriter
{
    private static readonly Foo instance = new Foo( "D:/tmp/test" );

    private Foo( string path )
        : base( path )
    {
    }

    ~Foo()
    {
        this.Close();
    }

    public static Foo Instance
    {
        get
        {
            return instance;
        }
    }
}

预期的效果是

class Program
{
    private static void Main( string[] args )
    {
        Foo.Instance.Write( "asdf\n" );
    }
}

垃圾收集器导致<$ c $的实例c> Foo 将被关闭。

the garbage collector causes the instance of Foo to be closed.

这不起作用。显然,当 Foo 的析构函数运行时, StreamWriter 已经消失了,我得到了 System.ObjectDisposedException

This does not work. Apparently, the StreamWriter is already gone when Foo's destructor runs, and I get a System.ObjectDisposedException.

如何在流中调用 Close()一种合适的方法并防止数据丢失?

How do I call Close() on the stream in an appropiate way and prevent loss of data?

推荐答案


显然,当Foo的StreamWriter已经消失了析构函数运行

Apparently, the StreamWriter is already gone when Foo's destructor runs

是。在程序终止时,假设您的对象完全获得了GC处理(不保证会得到),则运行时不会保证其执行终结器的顺序。这两个对象都无法访问且可以同时终结,因此它们的终结器可以按任何顺序运行。

Yes. At program termination, assuming your object gets GC'ed at all (there's no guarantee it will be), the runtime doesn't provide any guarantees about the order in which it executes finalizers. Both objects are unreachable and eligible for finalization at the same time, and so their finalizers could run in any order.

最终终结器仅 错误代码的支持。而且,它们也不是100%可靠的。这就是为什么您应该努力避免错误代码的原因。

Finalizers are there only as a backstop for buggy code. And they are not 100% reliable for that purpose either. It's why you should work hard to avoid buggy code.

您将需要一种确定性的方法来在流程出口处放置单例对象。您可以将其置于程序的主要逻辑中,该逻辑控制着进程的生命周期,并让它处理单例(例如,通过为此目的编写的公共方法)。另一种选择是订阅单例构造函数中的 AppDomain.ProcessExit 事件,并让处理程序在那里关闭单例。

You'll need a deterministic way to dispose the singleton object on process exit. You can put this into the control of your program's main logic, which is controlling the process lifetime, and have it dispose the singleton (e.g. via a public method you write for that purpose). Another alternative is to subscribe to the AppDomain.ProcessExit event in your singleton's constructor, and have the handler close the singleton there.

有关其他信息,请参阅以下相关问题:

如何确保在应用程序之前将对象放在单例中关闭?

C#中的一次性单例

See these related questions for additional information:
How can I ensure that I dispose of an object in my singleton before the application closes?
Disposable singleton in C#

这篇关于自关闭StreamWriter单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆