我可以更新从后台线程的用户界面,为什么呢? [英] I can update UI from background thread, why?

查看:115
本文介绍了我可以更新从后台线程的用户界面,为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家都知道,从后台线程更新界面是不允许的(或不?)



我做了一个小实验。下面是一段代码:

  VAR线程=新主题(()=> progressBar1.Increment(50)); 
thread.IsBackground = TRUE;
thread.Start();
的Thread.join();



我把这个代码在某些按钮单击处理程序。而知道吗?我的进度是递增......从后台线程。现在我很困惑。我不明白它是如何可能的,什么我做错了。


解决方案

我可以更新从后台线程,为什么?


$ b $用户接口b

最有可能可以在调试器外运行时做到这一点。这是因为保护由 Control.CheckForIllegalCrossThreadCalls物业的。让我们来看看参考源

 私有静态布尔checkForIllegalCrossThreadCalls = Debugger.IsAttached; 
公共静态布尔CheckForIllegalCrossThreadCalls {
{返回checkForIllegalCrossThreadCalls; }
集合{checkForIllegalCrossThreadCalls =价值; }
}

你可能会看到,这种保护默认情况下,只有当你启用调试。



如果您添加在你的办法(以下行之前 Application.Run

  Control.CheckForIllegalCrossThreadCalls = TRUE; 



你的代码将不再工作。


Everybody knows, that updating UI from background thread is not allowed (or not?)

I did a little experiment. Here is a piece of code:

var thread = new Thread(() => progressBar1.Increment(50));
            thread.IsBackground = true;
            thread.Start();
            thread.Join();

I put this code in some button click handler. And know what? My progressbar is incrementing...From background thread. And now I am confused. I don't understand how it is possible and what am I doing wrong

解决方案

I can update UI from background thread, why?

Most probably you can do that when running outside the debugger. This is because that protection is controlled by the Control.CheckForIllegalCrossThreadCalls Property. Let take a look at reference source

private static bool checkForIllegalCrossThreadCalls = Debugger.IsAttached;
public static bool CheckForIllegalCrossThreadCalls {
    get { return checkForIllegalCrossThreadCalls; }
    set { checkForIllegalCrossThreadCalls = value; }
}

As you may see, this protection is enabled by default only when you are debugging.

If you add the following line in your Main method (before Application.Run)

Control.CheckForIllegalCrossThreadCalls = true;

your code will not work anymore.

这篇关于我可以更新从后台线程的用户界面,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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