非UI线程操作UI
如果你開發(fā)過Windows Form項(xiàng)目,并使用過多線程操作UI,那么我相信你應(yīng)該熟悉上面這段代碼,在非UI線程操作UI。
當(dāng)你用F5 debug模式運(yùn)行此項(xiàng)目,并點(diǎn)擊button1運(yùn)行此段代碼時(shí),你將會(huì)看到這個(gè)異常信息:
?
但是在我們使用Ctrl+F5或者直接到項(xiàng)目輸出目錄執(zhí)行程序,并點(diǎn)擊button1的時(shí)候,label1的內(nèi)容被修改成功了,并且沒有任何異常被拋出。
這是為什么呢?
一位英文名叫Xiao Liang 來自 MSRA 的工程師告訴我 most Windows native APIs / messages are thread-safe.(在非UI線程操作UI會(huì)有潛在的問題,當(dāng)兩個(gè)線程在同一時(shí)間索取這個(gè)控件的話,問題就會(huì)油然而生了,呵呵)我們可以在非UI線程操作這個(gè)label1. 他還發(fā)現(xiàn), “Control.CheckForIllegalCrossThreadCalls? is True?? with debugger,???? False? without debugger”. OK,主要的原因找到了,關(guān)鍵就是這個(gè)Control.CheckForIllegalCrossThreadCalls property.
當(dāng)有詢問Xiao Liang我是否可以把他的這個(gè)研究結(jié)果公布在我的blog文章里時(shí),他發(fā)給我了一片MSDN文章,說這篇文章說得比較清晰:
我讀過這篇文章不知道多少遍了,但就是沒有注意到下面這段話:
http://msdn.microsoft.com/en-us/library/ms171728.aspx
This exception occurs reliably during debugging and, under some circumstances, at run time. You might see this exception when you debug applications that you wrote with the .NET Framework prior to the .NET Framework version 2.0. You are strongly advised to fix this problem when you see it, but you can disable it by setting the CheckForIllegalCrossThreadCalls property to false. This causes your control to run like it would run under Visual Studio .NET 2003 and the .NET Framework 1.1.
At last, I think I should thanks Xiao Liang at the end of this blog article.
最后,我想在這篇blog文章的末尾再次感謝Xiao Liang。
轉(zhuǎn)載于:https://www.cnblogs.com/telnet_mike/archive/2011/10/11/2207655.html
總結(jié)
- 上一篇: voc定位数据xml转coco数据集格式
- 下一篇: step2 . day5 C语言中的结构