我刚学会了如何在单独的线程中设置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”完成后,在我在“这里”显示的行 - 在xMethod_Finish中。看起来有一些不匹配的参数 - 但我认为我们都认为它们都是正确的 - 我花了很多精力来理解如何将参数传递给委托,以便它们也可以在EndInvoke之后传递给后续方法第一个(仍将在GUI线程中)。
请帮我看看我做错了什么。谢谢。
答案 0 :(得分:1)
您的调用看起来是正确的。
错误可能出现在yMethod
或myGui.Finish()
方法中。当异常在调用的方法中出现时,异常会变得有点隐藏。检查异常的InnerException
属性以获取更多信息以及导致KeyNotFoundException
的原因的堆栈跟踪。
您可以在问题方法中设置断点来调试错误。