我刚刚学会了如何在单独的线程中设置 GUI...
Private myGui As SomeGui
Public Class myAsyncState
Public a As Boolean = True
Public b As Integer = 100
End Class
Public Sub Caller()
'
myGui = New SomeGui()
' setup
myGui.Begin()
Dim a as Boolean = False
Dim b as Integer = 1
Dim state As myAsyncState = New myAsyncState(a, b)
Dim step1 As New xDelegate(AddressOf xMethod)
Dim callBack As New AsyncCallback(AddressOf xMethod_Callback)
Dim asyncResultTest As IAsyncResult = step1.BeginInvoke(a, b, callBack, state)
End Sub
Private Delegate Sub xDelegate(Byval a as Integer, ByVal b As Boolean)
Public Sub xMethod(Byval a as Integer, ByVal b As Boolean)
End Sub
Private Sub xMethod_Callback(ByVal ia As IAsyncResult)
Dim myAsyncResult As AsyncResult = CType(ia, AsyncResult)
Dim myAsyncMethodCaller As xDelegate = CType(myAsyncResult.AsyncDelegate, xDelegate)
Dim state As myAsyncState = CType(myAsyncResult.AsyncState, myAsyncState)
myAsyncMethodCaller.EndInvoke(ia)
xMethod_Finish(state.a, state.b)
End Sub
Private Sub xMethod_Finish(ByVal a As Integer, ByVal b As Boolean)
If Me.InvokeRequired Then
Invoke(New xDelegate(AddressOf xMethod_Finish), New Object() {a, b}) ' here
' Also tried Invoke(New xDelegate(AddressOf xMethod_Finish), a, b) though the above is what I have seen in documentation
' also tried to make Dim state As myAsyncState = New myAsyncState(a, b) and use it as an argument
Else
yMethod(a, b)
myGui.Finish()
End If
End Sub
我正在返回和传递值,一切都很好......然后我返回它进行测试,并得到一个错误:
A first chance exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
An unhandled exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in System.Windows.Forms.dll
Additional information: The given key was not present in the dictionary.
例外是在“xMethod”完成后,在我显示“here”的那一行 - 在 xMethod_Finish 中。看起来有一些不匹配的参数 - 但我认为它们都是正确的 - 我付出了很多努力来理解如何将参数传递给委托,以便它们也可以在 EndInvoke 之后传递给后续方法第一个(仍将在 GUI 线程中)。
请帮我看看我做错了什么。谢谢你。