WPF从其他线程访问GUI [英] WPF access GUI from other thread

查看:72
本文介绍了WPF从其他线程访问GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在满足仅使WPF应用程序成为单个实例的要求. 但是-我必须将命令行传递给第一个实例,然后执行一些UI操作.

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.

我正在使用Mutext检查已经运行的实例,我确实使用NamedPipes将命令行传输到已经运行的实例.

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.

但是,我当然不在访问"Window1"的正确线程中. 我试图在静态类中存储对"Window1"的引用,然后使用分派器在"Window1"中调用方法,但是,一旦我尝试访问变量("Window1"中的类范围很广),我就会收到对象引用未设置为对象的实例."

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

UI操作是将新的Tab添加到TabControl-在新Tab的初始化过程中已完成一些工作-并初始化了变量,甚至我想调用的方法在初始化过程中也都可以工作-但从调度程序失败.

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?

谢谢!

推荐答案

这很简单:

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

您可以从App.Startup以及从命名管道接收消息的线程中调用它.

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. 使用BeginInvoke代替Invoke来防止调用线程等待
  2. 使用DispatcherPriority.ApplicationIdle来确保应用程序在处理命令行之前已完成初始化
  3. 在尚未初始化Window1的情况下,使用Application.Current.Dispatcher代替Window1.Dispatcher

这篇关于WPF从其他线程访问GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆