WPF access GUI from other thread

后端 未结 2 794
-上瘾入骨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条回答
  •  萌比男神i
    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

提交回复
热议问题