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

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

问题描述

我最近在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;

是的,我知道这是pretty跛但这些简单的监控应用。

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

事实上,现在我正在在后台检索数据的WPF应用程序,我开始一个新的线程进行调用来检索(从Web服务器)中的数据,现在我想要显示它在我的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:结果
 的所以我使用了新胎时,我得到了这个数据的方法调度?或者我应该做一个后台工作检索数据,把它放入一个字段,并开始一个新的线程等待,直到这个领域充满并调用调度显示检索到的数据进入控制?

推荐答案

的第一件事就是要明白,分派没有设计运行长阻塞操作(例如从Web服务器检索数据...)。当你想运行将在UI线程上执行的操作(如更新进度条的值),你可以使用调度。

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.

如果你确实需要直接使用分派器,它是pretty简单:

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));

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

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