如何:异步调用远程对象的方法
异步编程的过程与单个应用程序域的过程一样简单。
异步调用远程对象的方法
创建可以接收对方法进行的远程调用的对象实例。
用 AsyncDelegate 对象包装该实例方法。
Dim RemoteCallback As New AsyncCallback(AddressOf Me.OurCallBack)
AsyncCallback RemoteCallback = new AsyncCallback(this.OurCallBack);
用另外一个委托包装该远程方法。
Dim RemoteDel As New RemoteAsyncDelegate(AddressOf obj.RemoteMethod)
RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(obj.RemoteMethod);
在第二个委托上调用 BeginInvoke 方法,并传递所有参数、AsyncDelegate 和某个保持状态的对象(或空引用,在 Visual Basic 中为 Nothing)。
Dim RemAr As IAsyncResult = RemoteDel.BeginInvoke(RemoteCallback, _ Nothing)
IAsyncResult RemAr = RemoteDel.BeginInvoke(RemoteCallback, null);
等待服务器对象调用您的回调方法。
尽管这是常规方法,但可以在一定程度上改变它。如果要在任何时候等待某个特定调用返回,只需要获取从 BeginInvoke 调用返回的 IAsyncResult 接口,检索该对象的 WaitHandle 实例,然后调用 WaitOne 方法,如下面的代码示例中所示。
RemAr.AsyncWaitHandle.WaitOne()
RemAr.AsyncWaitHandle.WaitOne();
或者,您可以在检查该调用是否已完成的循环中(或者通过使用 System.Threading 基元,如 ManualResetEvent 类)等待,然后自行结束调用,如下面的示例代码中所示。
If RemAr.IsCompleted Then Dim del As RemoteAsyncDelegate = CType(CType(RemAr, AsyncResult).AsyncDelegate, RemoteAsyncDelegate) Console.WriteLine(("SUCCESS: Result of the remote AsyncCallBack:" _ + del.EndInvoke(RemAr))) ' Allow the callback thread to interrupt the primary thread to execute the callback. Thread.Sleep(1) End If ' Do something.
if (RemAr.IsCompleted){ RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult) RemAr).AsyncDelegate; Console.WriteLine("SUCCESS: Result of the remote AsyncCallBack: " + del.EndInvoke(RemAr) ); // Allow the callback thread to interrupt the primary thread to execute the callback. Thread.Sleep(1); }
最后,可以使主线程创建 ManualResetEvent 并且等待回调函数,然后,回调函数将在返回前的最后一行向 ManualResetEvent 发出信号。有关此类型等待的示例,请参见远程处理示例:异步远程处理中的源代码注释。