如果要从非UI线程设置表单的Text属性,则需要使用Invoke来避免跨线程错误。但是,我可以在不使用调用的情况下读取Text属性。这安全吗?如果我试图读取表单的句柄属性,就会得到一个交叉线程错误。如果我读取表单的IsDisposed属性,它就能正常工作。如何判断何时需要使用调用?应该始终使用来读取和写入属性值吗?
发布于 2009-02-11 19:08:51
最简单的方法是使用:
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代码..。
发布于 2009-02-11 19:59:52
另一种选择是使用SynchronizationContext。这不仅适用于WinForms,也适用于WPF和ASP.NET,而且从.NET 2.0开始就可以使用了。
在主线程上调用SynchronizationContext.Current (例如在构造函数中),并在需要同步调用时使用返回的对象。如果对象为null,则不需要同步。
https://stackoverflow.com/questions/538251
复制相似问题