开发者

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开发者_如何学Go an application shutdown?

Thanks!


System.Environment.HasShutdownStarted

Documentation here: http://msdn.microsoft.com/en-us/library/system.environment.hasshutdownstarted.aspx


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜