更新用户界面从多个工作线程(.NET) [英] Update UI from multiple worker threads (.NET)

查看:100
本文介绍了更新用户界面从多个工作线程(.NET)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个宠物项目,我的工作有多个工作线程。一切输出到控制台越来越难追,所以我想开发一个用户界面,将有每个线程一个输出区。我想知道的线程更新发送到UI的最佳方式。我有两个想法:

I have a pet project that I'm working on that has multiple worker threads. Outputting everything to the console is getting hard to follow, so I want to develop a UI that will have one output area per thread. I want to know the best way for the threads to send updates to the UI. I have two ideas:

1)让每个线程设置当新数据可用一个DataUpdated标志,并有UI定期检查新数据。

1) Have each thread set a "DataUpdated" flag when new data is available, and have the UI periodically check for new data.

2)创建每个线程有一个回调到UI更新(...)方法被调用时,新的数据可用。

2) Create each thread with a callback to a UI Update(...) method to be called when new data becomes available.

我目前对倾斜(2)原因有二:我不喜欢检查每个线程的想法,因为这是我的第一个多线程应用程序和(2)似乎更简单的比它可能是。我想知道的:

I am currently leaning toward (2) for two reasons: I dislike the idea of "checking" each thread, and because this is my first multithreaded application and (2) seems simpler than it probably is. I want to know:

  • 在哪个选项是preferable在简单和效率?
  • 条款
  • 请您对执行(2)或类似的东西任何提示它(即更多的事件驱动)?

推荐答案

您可以轻松实现(2)通过创建BackgroundWorker的组件和做的工作在他们的DoWork的处理程序:

You can easily implement (2) by creating BackgroundWorker components and doing the work in their DoWork handlers:

BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.DoWork += /* your background work here */;
bw.ProgressChanged += /* your UI update method here */;
bw.RunWorkerAsync();

每个BackgroundWorker的可以报告进度到UI线程调用ReportProgress:虽然这主要是用来在有界进程报告进展情况,这不是强制性的 - 你可以通过自己的自定义数据,以及如果这就是你的UI更新需要。你会打电话ReportProgress从DoWork的处理程序。

Each BackgroundWorker can report progress to the UI thread by calling ReportProgress: although this is primarily designed for reporting progress on a bounded process, that's not mandatory -- you can pass your own custom data as well if that's what your UI update requires. You would call ReportProgress from your DoWork handler.

有关的BackgroundWorker的好处是,它需要很多乱七八糟的跨线程的详细信息,你的照顾。它还符合最新的事件驱动模型,你(正确地)preFER以明确的回调。

The nice thing about BackgroundWorker is that it takes care of a lot of messy cross-threading details for you. It also conforms to the event-driven model of updates which you (rightly) prefer to explicit callbacks.

这篇关于更新用户界面从多个工作线程(.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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