1

別のスレッドで 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 スレッドにあります)。

私が間違っていることを教えてください。ありがとうございました。

4

1 に答える 1

1

あなたの呼び出しは正しいようです。

yMethodまたはmyGui.Finish()メソッドでエラーが発生している可能性があります。呼び出されたメソッドで例外が発生すると、例外が少し隠れる場合があります。例外のInnerExceptionプロパティをチェックして、より多くの情報を取得し、原因のスタック トレースを取得しますKeyNotFoundException

問題のメソッドにブレークポイントを設定して、エラーをデバッグできます。

于 2013-01-29T00:08:44.180 に答える