Accessing Application.Current from a different thread in a static class constructor RRS feed

  • Question

  • I've got this static constructor in a singleton class.  I have multiple UI threads.  When the constructor tries to attach to the Application.Current.Exit  event, I get a TypeInitializationException in the calling code with an InvalidOperation inner exception of "The calling thread cannot access this object because a different thread owns it."

    The documentation for Application.Current states that it is accessible from any thread.  The static constructor is being called by a UI thread that I created.  Things work well if I comment out the Application.Current.Exit subscription. 

    Any ideas what's wrong?

    class StaticClass{
        static StaticClass()
          Application.Current.Exit += new ExitEventHandler(Application_Exit);
        static void Application_Exit(object sender, ExitEventArgs e)
        public void SaveSettings(){}
    Tuesday, April 19, 2011 3:27 PM


  • I was able to work around the problem by changing the Application.Current.Exit line to:

      ()=> Application.Current.Exit += new ExitEventHandler(Application_Exit)
    ), new object[]{});
    • Marked as answer by CalebD Wednesday, April 20, 2011 3:49 PM
    Wednesday, April 20, 2011 3:49 PM