Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

c# - 如何从另一个线程更新GUI?(How do I update the GUI from another thread?)

What is the simplest way to update a Label from another thread?

(从另一个线程更新Label的最简单方法是什么?)

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

(我在thread1上有一个Formthread1开始,我开始了另一个线程( 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.

(当thread2处理某些文件时,我想使用thread2的当前状态更新Form上的Label 。)

How can I do that?

(我怎样才能做到这一点?)

  ask by CruelIO translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(最简单的方法是将匿名方法传递给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

Notice that Invoke blocks execution until it completes--this is synchronous code.

(请注意, Invoke阻止执行直到完成为止-这是同步代码。)

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.

(这个问题并没有询问异步代码,但是您想了解异步代码时,Stack Overflow上有很多内容涉及编写异步代码。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...