4

Is there an Unload event, or any event, notification, message, mechanism, or hook, that i can use to be notified before the "default" application domain is unloaded?

i have code that needs to know when the application domain (almost always the default domain) is ending.

Note: i don't know what kind of application a developer will be creating when he uses my code. It could be:

  • a console application
  • a WinForms application
  • an ASP.net application
  • an ASP.net web-site
  • Runtime Callable Wrapper (RCW) COM object
  • a Windows Explorer shell extension
  • or a Windows Service

Either way, i need to know when the domain is closing, so i can do some "stuff". And i am not going to require the user to call any sort of "Shutdown" or "Cleanup" method. (Also, suggesting that the user be required to call a method themselves doesn't answer the question: which is about being notified when the app domain i'm running in is shut down).

See also

4

2 回答 2

8

我忘了从这个问题的其他细微变化中交叉发布我自己的答案。最终,答案来自MA Hanin 的回答

没有DomainUnload,但有一个ProcessExit

class Contoso
{
   //constructor
   public Contoso()
   {
      //...

      //Catch domain shutdown (Hack: frantically look for things we can catch)
      if (AppDomain.CurrentDomain.IsDefaultAppDomain())
         AppDomain.CurrentDomain.ProcessExit += MyTerminationHandler;
      else
         AppDomain.CurrentDomain.DomainUnload += MyTerminationHandler;
   }

   private void MyTerminationHandler(object sender, EventArgs e)
   {
      //The domain is dying. Serialize out our values
      this.Dispose();
   }

   ...
}

注意:任何代码都会发布到公共领域。无需归属。

于 2013-09-06T18:20:50.653 回答
4
AppDomain.CurrentDomain.DomainUnload += 
    (object sender, EventArgs e) => { /*do stuff*/ };
于 2014-10-01T01:39:16.607 回答