如何从另一个线程更新GUI

如何从另一个线程更新GUI

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

问题描述

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

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

  • 我有一个在thread1上运行的Form,从此我启动了另一个线程(thread2).

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

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

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 12:56