您需要让 UI 线程调用 frmMain.refreshStats 方法。当然,有很多方法可以使用 Control.InvokeRequired 属性和 Control.Invoke(MSDN 文档)来执行此操作。
您可以让“EndAsync”方法使方法调用 UI 线程安全,或者让 refreshStats 方法检查线程安全(使用 Control.InvokeRequired)。
EndAsync UI 线程安全将是这样的:
Public Delegate Sub Method(Of T1, T2)(ByVal arg1 As T1, ByVal arg2 As T2)
Sub skDataReceived(ByVal result As IAsyncResult)
Dim frmMain As Form = CType(My.Application.OpenForms.Item("frmMain"), frmMain)
Dim d As Method(Of Object, Object)
'create a generic delegate pointing to the refreshStats method
d = New Method(Of Object, Object)(AddressOf frmMain.refreshStats)
'invoke the delegate under the UI thread
frmMain.Invoke(d, New Object() {d1, d2})
End Sub
或者你可以让 refreshStats 方法检查它是否需要在 UI 线程下调用自己:
Public Delegate Sub Method(Of T1, T2)(ByVal arg1 As T1, ByVal arg2 As T2)
Sub refreshStats(ByVal d1 As Object, ByVal d2 As Object)
'check to see if current thread is the UI thread
If (Me.InvokeRequired = True) Then
Dim d As Method(Of Object, Object)
'create a delegate pointing to itself
d = New Method(Of Object, Object)(AddressOf Me.refreshStats)
'then invoke itself under the UI thread
Me.Invoke(d, New Object() {d1, d2})
Else
'actual code that requires UI thread safety goes here
End If
End Sub