C#:在终结器中,如何确定应用程序是否正在关闭?

发布于 2024-11-02 07:20:38 字数 101 浏览 5 评论 0原文

我有一个终结器,在应用程序关闭期间似乎总是失败。我认为这是因为它保留了一些此时不再有效的本机资源。有没有办法在析构函数/终结器中判断它是否由于应用程序关闭而被调用?

谢谢!

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

晨曦慕雪 2024-11-09 07:20:38

我想 AppDomain.IsFinalizingForUnload() 将提供此信息。

I would imagine that AppDomain.IsFinalizingForUnload() would provide this info.

天涯沦落人 2024-11-09 07:20:38

如果它们已经被处理掉了,你真的需要在终结器中处理掉它们吗?
或者反过来:您是否可以通过 IDisposable 模式来处理它们?

即使它是您在应用程序的整个生命周期中保留的资源,您仍然可以将其放入使用中:

static void Main()
{
  using(var yourResource = ...)
  {
     ...
     yourMainForm.YourResource = yourResource;
     Application.Run...
  }
}

编辑:除了一些有趣的答案[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:

static void Main()
{
  using(var yourResource = ...)
  {
     ...
     yourMainForm.YourResource = yourResource;
     Application.Run...
  }
}

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文