如何从另一个线程更新 GUI? [英] How do I update the GUI from another thread?

查看:43
本文介绍了如何从另一个线程更新 GUI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从另一个 Thread 更新 Label 的最简单方法是什么?

Which is the simplest way to update a Label from another Thread?

  • 我有一个 Formthread1 上运行,然后我开始另一个线程 (thread2).

  • I have a Form running on thread1, and from that I'm starting another thread (thread2).

thread2 正在处理一些文件时,我想用 的当前状态更新 Form 上的 Label>thread2 的工作.

While thread2 is processing some files I would like to update a Label on the Form with the current status of thread2's work.

我怎么能这样做?

推荐答案

最简单的方式是将匿名方法传递给 Label.Invoke:

The simplest way is an anonymous method passed into Label.Invoke:

// Running on the worker thread
string newText = "abc";
form.Label.Invoke((MethodInvoker)delegate {
    // Running on the UI thread
    form.Label.Text = newText;
});
// Back on the worker thread

注意 Invoke 会阻塞执行直到它完成——这是同步代码.这个问题不问异步代码,但有很多关于堆栈溢出的内容 关于在您想了解异步代码时编写异步代码.

Notice that Invoke blocks execution until it completes--this is synchronous code. The question doesn't ask about asynchronous code, but there is lots of content on Stack Overflow about writing asynchronous code when you want to learn about it.

这篇关于如何从另一个线程更新 GUI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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