强制从 UI 线程更新 GUI [英] Force GUI update from UI Thread
问题描述
在 WinForms 中,如何从 UI 线程强制立即更新 UI?
In WinForms, how do I force an immediate UI update from UI thread?
我正在做的大致是:
label.Text = "Please Wait..."
try
{
SomewhatLongRunningOperation();
}
catch(Exception e)
{
label.Text = "Error: " + e.Message;
return;
}
label.Text = "Success!";
标签文本在操作前未设置为请稍候...".
Label text does not get set to "Please Wait..." before the operation.
我使用另一个线程解决了这个问题,但它变得很麻烦,我想简化代码.
I solved this using another thread for the operation, but it gets hairy and I'd like to simplify the code.
推荐答案
起初我想知道为什么 OP 还没有将其中一个响应标记为答案,但是在我自己尝试之后仍然无法正常工作,我挖得更深一些,发现这个问题比我最初想象的要多得多.
At first I wondered why the OP hadn't already marked one of the responses as the answer, but after trying it myself and still have it not work, I dug a little deeper and found there's much more to this issue then I'd first supposed.
通过阅读类似的问题可以获得更好的理解:为什么赢了'不控制更新/刷新中间过程
A better understanding can be gained by reading from a similar question: Why won't control update/refresh mid-process
最后,作为记录,我能够通过执行以下操作来更新我的标签:
Lastly, for the record, I was able to get my label to update by doing the following:
private void SetStatus(string status)
{
lblStatus.Text = status;
lblStatus.Invalidate();
lblStatus.Update();
lblStatus.Refresh();
Application.DoEvents();
}
尽管据我所知,这远不是一种优雅而正确的方法.这是一个 hack,可能会或可能不会起作用,具体取决于线程的繁忙程度.
Though from what I understand this is far from an elegant and correct approach to doing it. It's a hack that may or may not work depending upon how busy the thread is.
这篇关于强制从 UI 线程更新 GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!