Self-closing StreamWriter singleton

那年仲夏 提交于 2019-12-02 04:08:29
Peter Duniho

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

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.

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.

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.

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#

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!