C#垃圾收集器似乎太早结束我的StreamWriter我的、太早、垃圾、结束

由网友(捞起月亮的渔民)分享简介:我有一个记录器类那是一个单例。在它的析构函数中我调用Close(),它打印页脚的日志,然后关闭的StreamWriter。I have a logger class thats a singleton. In it's destructor I call Close() which prints the footer...

我有一个记录器类那是一个单例。在它的析构函数中我调用Close(),它打印页脚的日志,然后关闭的StreamWriter。

I have a logger class thats a singleton. In it's destructor I call Close() which prints the footer for the log and then closes the StreamWriter.

 public void Close()
    {
        WriteLogFileFooter();

        _logFile.Flush();

        _logFile.Close();
    }

现在的问题是,当System.Enviornment.Exit(1)是从其他地方调用程序(部分我没写我自己),页脚从不打印并试图写一个我的记录器抛出一个异常关闭的流。我只能假设Exit命令导致之前我辛格尔顿被破坏我的StreamWriter关闭。我想在我的StreamWriter使用GC.Su pressFinalize(),但似乎并没有帮助。

The problem is when System.Enviornment.Exit(1) is called from elsewhere in the program (portions that I didn't write myself), the footer is never printed and my logger throws an exception for trying to write to a closed stream. I can only assume the Exit command is causing my StreamWriter to be closed before my Singleton is destructed. I tried to use GC.SupressFinalize() on my StreamWriter but that didn't seem to help.

推荐答案

您违反了一个明确的规则终结:

You are violating one explicit rule for finalizers:

finalize方法不应该引用任何其他对象。

The Finalize method should not reference any other objects.

http://msdn.microsoft.com/en-us/library/b1yfkh5e(v=VS.90).aspx

这是完全有可能的,您有一个参考的管理对象被收集到之前,你的目标是收集到的应用程序退出的时候。

It's entirely possible that the managed object you hold a reference to is collected before your object is collected when the application exits.

更新

如果您需要清理托管资源,应用程序退出时,你可以挂接的的AppDomain ProcessExit 的事件,而不是依赖于终结执行的不确定性的行为。

If you need to clean up managed resources when the application exits, you could hook up the ProcessExit event of AppDomain rather than rely on non-deterministic behavior of finalizer execution.

.NET控制台应用程序退出事件

阅读全文

相关推荐

最新文章