从一个异步回调方法UI线程交互? [英] Interacting with the UI thread from an Async callback method?

查看:451
本文介绍了从一个异步回调方法UI线程交互?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个是异步调用时的 System.Net.Sockets.NetworkStream.BeginRead 结束。

I have a method that is asynchronously called when System.Net.Sockets.NetworkStream.BeginRead completes.

 skDelegate = New AsyncCallback(AddressOf skDataReceived)
 skStream.BeginRead(skBuffer, 0, 100000, skDelegate, New Object)

在该回调的方法,我需要与UI线程交互。

In that callback method, I need to interact with the UI thread.

Sub skDataReceived(ByVal result As IAsyncResult)
    CType(My.Application.OpenForms.Item("frmMain"), frmMain).refreshStats(d1, d2)
End Sub

这会使方法完成后异常。 (当执行完子)

This causes an exception after the method completes. (when End Sub is executed)

遇到的撤消操作
  背景下,是什么不同
  在相应的设置应用于
  操作。可能的原因是,
  一个背景下设置的线程上和
  尚未归还(撤消)。

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线程交互?我在做什么错了?

So how do I interact with the UI thread from the callback method? What am I doing wrong?

推荐答案

您必须使用调用或BeginInvoke的frmMain对象上排队的消息(委托)到UI线程上执行。

You have to use Invoke or BeginInvoke on the frmMain object to enqueue a message (a delegate) to execute on the UI thread.

下面就是我会做它在C#。

Here's how I'd do it in C#.


frmMain.Invoke(() => frmMain.refreshStats(d1, d2));

另外,请检查该<一个href=\"http://stackoverflow.com/questions/229554/whats-the-difference-between-invoke-and-begininvoke\">list援引类型及其使用的。

这篇关于从一个异步回调方法UI线程交互?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆