Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
450 views
Welcome To Ask or Share your Answers For Others

1 Answer

i forgot to cross post my own answer from my other slight variation of this question. Ultimately, the answer came from an answer by M.A. Hanin.

There is no DomainUnload, but there is a 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();
   }

   ...
}

Note: Any code is released into the public domain. No attribution required.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...