WPF access GUI from other thread

ε祈祈猫儿з 提交于 2019-12-20 03:14:06

问题


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 action.

I am using a Mutext to check for already running instances, I do use NamedPipes to transfer the command line to the already running instance.

But of course I am not in the correct Thread to access "Window1". I tried to store a reference to "Window1" in a static class and then use the Dispatcher to call a Method in "Window1", however, as soon as I try to access a variable (class wide scope in "Window1") I receive a "Object reference not set to an instance of an object."

The UI Action is to add a new Tab to a TabControl - during initialization of the new Tab some work is done - and the variables are initialized and even the method I want to call works during the init - but when called from the Dispatcher it fails.

Any hints, how to do this? Am I on the wrong track here?

Thanks!


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/2363920/wpf-access-gui-from-other-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!