GUI not updating until code is finished(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?
推荐答案
一个丑陋的 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 在代码完成之前不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:GUI 在代码完成之前不会更新


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01