2009-02-11 38 views
1

如果我從非UI線程設置表單的Text屬性,那麼我需要使用Invoke來避免跨線程錯誤。但是,我可以讀取Text屬性而不使用Invoke。這安全嗎?如果我嘗試讀取表單的Handle屬性,則會出現交叉線程錯誤。如果我閱讀表單的IsDisposed屬性,它工作正常。如何知道何時需要使用Invoke?我應該總是使用調用來讀取和寫入屬性值?如何判斷屬性是否需要調用?

回答

4

無論何時您在UI線程中使用其他線程時,都應該在訪問UI對象時使用Invoke。使用InvokeRequired屬性來查明您是否實際上處於不同的線程中。

+0

+1,你所尋找的方法(或屬性?)需要調用 – masfenix 2009-02-11 19:09:50

1

最簡單的方法是使用:

Delegate Sub SetTextCallback(ByVal [text] As String) 

Private Sub SetText(ByVal [text] As String) 
' InvokeRequired required compares the thread ID of the 
' calling thread to the thread ID of the creating thread. 
' If these threads are different, it returns true. 
If Me.lboxResults.InvokeRequired Then 
    Dim d As New SetTextCallback(AddressOf SetText) 
    Me.Invoke(d, New Object() {[text]}) 
Else 
    Me.lboxResults.Items.Add([text]) 
End If 

末次

很抱歉的VB代碼...

0

另一種選擇是使用的SynchronizationContext。這不僅適用於WinForms,也適用於WPF和ASP.NET,並且自.NET 2.0起可用。

在主線程(例如,在構造函數中)調用SynchronizationContext.Current,並在需要同步調用時使用返回的對象。如果對象爲空,則不需要同步。

相關問題