从UI线程力GUI更新 [英] Force GUI update from UI Thread

查看:152
本文介绍了从UI线程力GUI更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在的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.

我解决了这个使用另一个线程的操作,但它得到毛茸茸的,我想简化code。

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.

有一个更好的理解可以通过类似的问题,读来获得:为什么赢了'T控制更新/刷新中期过程

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();
}

虽然从我个人理解,这是远离优雅,正确的方法来这样做。这可能会或可能无法正常工作取决于线程的繁忙程度黑客攻击。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆