我有一个在 System.Net.Sockets.NetworkStream.BeginRead 时异步调用的方法完成。
skDelegate = New AsyncCallback(AddressOf skDataReceived)
skStream.BeginRead(skBuffer, 0, 100000, skDelegate, New Object)
在该回调方法中,我需要与 UI 线程进行交互。
Sub skDataReceived(ByVal result As IAsyncResult)
CType(My.Application.OpenForms.Item("frmMain"), frmMain).refreshStats(d1, d2)
End Sub
这会在方法完成后引发异常。 (当执行 End Sub 时)
The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone).
那么如何通过回调方法与 UI 线程进行交互呢?我做错了什么?
请您参考如下方法:
您必须在 frmMain 对象上使用 Invoke 或 BeginInvoke 来排队消息(委托(delegate))以在 UI 线程上执行。
以下是我在 C# 中的实现方式。
frmMain.Invoke(() => frmMain.refreshStats(d1, d2));
同时检查这个 list of Invoke types and their uses .
