我有一個主UI線程運行應用程序並創建主窗口窗體(我們稱之爲W
)。我還有一個輔助線程,我旋轉起來並創建一個對話框(我們稱之爲B
)。設置WinForms.Form所有者時出現跨線程異常 - 如何正確執行?
我想將對話框B
的所有者設置爲主窗口W
。所有者的設置B
發生在創建B
的線程上。基本上是:
b.Owner = w;
但這拋出一個跨線程異常告訴我,我tryng從錯誤的線程訪問W
對象。
所以我試圖通過使用W
上的Control.Invoke
來執行主UI線程上的代碼。但後來,我得到了同樣的錯誤,告訴我,我從錯誤的線程試圖訪問B
:
System.InvalidOperationException was unhandled by user code
Message=Cross-thread operation not valid: Control 'B' accessed from a
thread other than the thread it was created on.
Source=System.Windows.Forms
我怎麼做是正確的?
不要在多個線程上使用窗體。它會給你更多的麻煩,而不是它的價值。 – SLaks 2011-03-11 13:51:28
你讀過這個SO帖子:http://stackoverflow.com/questions/3046245/whats-wrong-with-my-cross-thread-call-in-windows-forms?如果這沒有幫助你,你應該發佈代碼給你的錯誤。 – 2011-03-11 13:51:29
也許您可以告訴我們您希望利用哪些所有權特徵(希望不是所有),並且我們可以建議實現類似效果的方法? – 2011-03-11 14:05:17