问题描述
嘿,我有一个类似这样的代码序列:
Hey, I have a sequence of code that goes something like this:
label.Text = "update 0";
doWork();
label.Text = "update 1";
doWork2();
label.Text = "update 2";
基本上,在所有代码执行完毕之前,GUI 根本不会更新.如何克服?
Basically, the GUI does not update at all, until all the code is done executing. How to overcome this?
推荐答案
一个丑陋的 hack 是使用 Application.DoEvents
.虽然这可行,但我建议不要这样做.
An ugly hack is to use Application.DoEvents
. While this works, I'd advise against it.
更好的解决方案是使用 BackgroundWorker
或单独的线程来执行长时间运行的任务.不要使用 GUI 线程,因为这会导致它阻塞.
A better solution is to use a BackgroundWorker
or a seperate thread to perform long running tasks. Don't use the GUI thread because this will cause it to block.
需要注意的重要一点是,必须在 GUI 线程上对 GUI 进行更改,因此您需要将控制权转移回 GUI 线程以进行标签更新.这是使用 Invoke
完成的.如果您使用 BackgroundWorker,则可以使用 ReportProgress - 这将自动为您处理调用 Invoke.
An important thing to be aware of is that changes to the GUI must be made on the GUI thread so you need to transfer control back to the GUI thread for you label updates. This is done using Invoke
. If you use a BackgroundWorker you can use ReportProgress - this will automatically handle calling Invoke for you.
这篇关于GUI 在代码完成之前不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!