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 在代码完成之前不会更新
基础教程推荐
- WPF 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
