WPF access GUI from other thread

后端 未结 2 766
-上瘾入骨i
-上瘾入骨i 2021-01-22 12:39

I am working through the requirement to make a WPF Application single instance only. However - I have to pass the command line to the first instance and then perform some UI act

相关标签:
2条回答
  • 2021-01-22 12:52

    This is easy:

    void ProcessCommandLine(string commandLine)
    {
      Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() =>
      {
        ... code to process the command line here ...
      });
    }
    

    You can call this from your App.Startup and also from your thread that receives messages from the named pipe.

    The key considerations here are:

    1. Use of BeginInvoke instead of Invoke to prevent the calling thread from waiting
    2. Use of DispatcherPriority.ApplicationIdle to guarantee the application has finished initializing before the command line is processed
    3. Use of Application.Current.Dispatcher instead of Window1.Dispatcher in case Window1 has not yet been initialzed
    0 讨论(0)
  • 2021-01-22 13:14

    That's not right, are you certain that the mutex is passing control correctly to your currently running instance of the application?

    If it was a thread UI access issue, you should have received this error: The calling thread cannot access this object because a different thread owns it.

    The fact that you're getting an "Object reference not set to an instance of an object." error message means that you've not yet instantiated the object as new.

    0 讨论(0)
提交回复
热议问题