非UI线程操作UI
如果你開發過Windows Form項目,并使用過多線程操作UI,那么我相信你應該熟悉上面這段代碼,在非UI線程操作UI。
當你用F5 debug模式運行此項目,并點擊button1運行此段代碼時,你將會看到這個異常信息:
?
但是在我們使用Ctrl+F5或者直接到項目輸出目錄執行程序,并點擊button1的時候,label1的內容被修改成功了,并且沒有任何異常被拋出。
這是為什么呢?
一位英文名叫Xiao Liang 來自 MSRA 的工程師告訴我 most Windows native APIs / messages are thread-safe.(在非UI線程操作UI會有潛在的問題,當兩個線程在同一時間索取這個控件的話,問題就會油然而生了,呵呵)我們可以在非UI線程操作這個label1. 他還發現, “Control.CheckForIllegalCrossThreadCalls? is True?? with debugger,???? False? without debugger”. OK,主要的原因找到了,關鍵就是這個Control.CheckForIllegalCrossThreadCalls property.
當有詢問Xiao Liang我是否可以把他的這個研究結果公布在我的blog文章里時,他發給我了一片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。
轉載于:https://www.cnblogs.com/telnet_mike/archive/2011/10/11/2207655.html
總結
- 上一篇: voc定位数据xml转coco数据集格式
- 下一篇: step2 . day5 C语言中的结构