C#:在终结器中,如何确定应用程序是否正在关闭?
我有一个终结器,在应用程序关闭期间似乎总是失败。我认为这是因为它保留了一些此时不再有效的本机资源。有没有办法在析构函数/终结器中判断它是否由于应用程序关闭而被调用?
谢谢!
I have a finalizer that seems to always fail during application shutdown. I think this is because it's holding onto some native resources that are no longer valid at that point. Is there a way to tell, in a destructor/finalizer, if it is being called due to an application shutdown?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此处的文档:http://msdn.microsoft.com/en-我们/library/system.environment.hasshutdownstarted.aspx
Documentation here: http://msdn.microsoft.com/en-us/library/system.environment.hasshutdownstarted.aspx
我想
AppDomain.IsFinalizingForUnload()
将提供此信息。I would imagine that
AppDomain.IsFinalizingForUnload()
would provide this info.如果它们已经被处理掉了,你真的需要在终结器中处理掉它们吗?
或者反过来:您是否可以通过 IDisposable 模式来处理它们?
即使它是您在应用程序的整个生命周期中保留的资源,您仍然可以将其放入使用中:
编辑:除了一些有趣的答案[1]之外,这听起来像是有一些东西整件事都是错误的。
如果终结器因资源已被释放而失败,则说明某处存在问题。
如果此资源对于正确处置至关重要,那么应该正确完成此操作。
我不确定“在用户界面中的某处引用”是否足够好。
做到正确并不难,即使这是在表单中完成的。您可以覆盖表单或组件或控制器的处置以确定性地执行此操作。
[1] 如果有一天它咬我的话可能会派上用场......
Do you really need to dispose of them in a finalizer if they are already disposed of otherwise?
Or the other way around: Isn't it possible for you to dispose of them via the IDisposable pattern?
Even if it is a resource that you grab hold on for the lifetime of your app, you can still put it into a using:
Edit: Apart from some interesting answers[1], this smells like there's something wrong about the whole thing.
If the finalizer fails because the resource has already been disposed of, then there's a problem somewhere.
If this resource is critical to be disposed of properly, then this should be done properly.
I'm not sure that "referenced somewhere in the UI" is good enough.
It isn't that hard to get right, even if this is done in Form or so. You can override the Form's or component's or controller's dispose to do it deterministically.
[1] Might come in handy if it bites me some day...