如何非同步呼叫遠端物件的方法
非同步程式設計的處理序,就如同單一應用程式定義域的程式設計一樣簡單。
若要非同步呼叫遠端物件的方法
建立可接收遠端方法呼叫的物件執行個體。
使用 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 和用於保存狀態的物件 (或 Null 參考;在 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,並在 callback 函式上等候,這個函式會接著在最後一行,發出信號至 ManualResetEvent,然後再返回。如需這類等候的範例,請參閱 遠端處理範例:非同步遠端處理 中的原始程式碼註解。