简体   繁体   中英

C#: In a finalizer, how to find out if the application is shutting down?

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!

System.Environment.HasShutdownStarted

文档: http//msdn.microsoft.com/en-us/library/system.environment.hasshutdownstarted.aspx

我想, AppDomain.IsFinalizingForUnload()会提供这个信息。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM