'System.Collections.Generic.KeyNotFoundException'在调用结束时



我刚刚学会了如何在单独的线程中设置 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 线程中)。

请帮助我看看我做错了什么。谢谢。

您的调用看起来是正确的。

错误可能出在yMethodmyGui.Finish()方法中。 当异常发生在调用的方法中时,它们可能会变得有点隐藏。 检查异常的 InnerException 属性以获取详细信息以及导致KeyNotFoundException的堆栈跟踪。

可以在问题方法中设置断点来调试错误。

相关内容

  • 没有找到相关文章

最新更新