直到代码完成,GUI才更新

问题描述:

嘿,我有一段代码是这样的:

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?

一个丑陋的方法是使用

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.