使用 Dispatcher.Invoke 从非主线程更改 WPF 控件 [英] Change WPF controls from a non-main thread using Dispatcher.Invoke

查看:27
本文介绍了使用 Dispatcher.Invoke 从非主线程更改 WPF 控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始用 WPF 编程,但遇到了以下问题.我不明白如何使用 Dispatcher.Invoke() 方法.我在线程方面有经验,并且我已经制作了一些简单的 Windows 窗体程序,我只是在其中使用了

I have recently started programming in WPF and bumped into the following problem. I don't understand how to use the Dispatcher.Invoke() method. I have experience in threading and I have made a few simple Windows Forms programs where I just used the

Control.CheckForIllegalCrossThreadCalls = false;

是的,我知道这很蹩脚,但这些都是简单的监控应用程序.

Yes I know that is pretty lame but these were simple monitoring applications.

事实是现在我正在制作一个在后台检索数据的 WPF 应用程序,我开始一个新线程来调用检索数据(从网络服务器),现在我想在我的 WPF 表单上显示它.问题是,我无法从该线程设置任何控制.甚至没有标签或任何东西.如何解决?

The fact is now I am making a WPF application which retrieves data in the background, I start off a new thread to make the call to retrieve the data (from a webserver), now I want to display it on my WPF form. The thing is, I cannot set any control from this thread. Not even a label or anything. How can this be resolved?

回答评论:
@Jalfp:
所以当我获取数据时,我会在新胎面"中使用这个 Dispatcher 方法?或者我应该让后台工作人员检索数据,将其放入一个字段并启动一个新线程,等待该字段被填充并调用调度程序将检索到的数据显示到控件中?

推荐答案

首先要了解的是,Dispatcher 并不是为运行长时间阻塞操作而设计的(例如从 WebServer 检索数据...).当您想要运行将在 UI 线程上执行的操作(例如更新进度条的值)时,您可以使用 Dispatcher.

The first thing is to understand that, the Dispatcher is not designed to run long blocking operation (such as retrieving data from a WebServer...). You can use the Dispatcher when you want to run an operation that will be executed on the UI thread (such as updating the value of a progress bar).

您可以做的是在后台工作程序中检索您的数据,并使用 ReportProgress 方法在 UI 线程中传播更改.

What you can do is to retrieve your data in a background worker and use the ReportProgress method to propagate changes in the UI thread.

如果你真的需要直接使用 Dispatcher,那很简单:

If you really need to use the Dispatcher directly, it's pretty simple:

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => this.progressBar.Value = 50));

这篇关于使用 Dispatcher.Invoke 从非主线程更改 WPF 控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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