AsyncResult 類的屬性
AsyncDelegate 獲取在其上調用異步調用的委托對象。Public property AsyncState獲取作為 BeginInvoke 方法調用的最后一個參數而提供的對象。
Public property AsyncWaitHandle獲取封裝 Win32 同步句柄並允許實現各種同步方案的 WaitHandle。
Public property CompletedSynchronously獲取一個值,該值指示 BeginInvoke 調用是否同步完成。
Public property EndInvokeCalled獲取或設置一個值,該值指示是否已在當前 AsyncResult 上調用 EndInvoke。
Public property IsCompleted獲取一個值,該值指示服務器是否已完成該調用。
Public property NextSink 獲取接收器鏈中的下一個消息接收器。
下面的代碼示例說明如何使用 AsyncResult 類檢索異步委托上的異步操作的結果。
using System; using System.Threading; using System.Runtime.Remoting; using System.Runtime.Remoting.Contexts; using System.Runtime.Remoting.Messaging; // Context-bound type with the Synchronization context attribute. [Synchronization()] public class SampleSyncronized : ContextBoundObject { // A method that does some work, and returns the square of the given number. public int Square(int i) { Console.Write("The hash of the thread executing "); Console.WriteLine("SampleSyncronized.Square is: {0}", Thread.CurrentThread.GetHashCode()); return i*i; } } // The async delegate used to call a method with this signature asynchronously. public delegate int SampSyncSqrDelegate(int i); public class AsyncResultSample { // Asynchronous Callback method. public static void MyCallback(IAsyncResult ar) { // Obtains the last parameter of the delegate call. int value = Convert.ToInt32(ar.AsyncState); // Obtains return value from the delegate call using EndInvoke. AsyncResult aResult = (AsyncResult)ar; SampSyncSqrDelegate temp = (SampSyncSqrDelegate)aResult.AsyncDelegate; int result = temp.EndInvoke(ar); Console.Write("Simple.SomeMethod (AsyncCallback): Result of "); Console.WriteLine("{0} in SampleSynchronized.Square is {1} ", value, result); } public static void Main() { int result; int param; // Creates an instance of a context-bound type SampleSynchronized. SampleSyncronized sampSyncObj = new SampleSyncronized(); // Checks whether the object is a proxy, since it is context-bound. if (RemotingServices.IsTransparentProxy(sampSyncObj)) Console.WriteLine("sampSyncObj is a proxy."); else Console.WriteLine("sampSyncObj is NOT a proxy."); param = 10; Console.WriteLine(""); Console.WriteLine("Making a synchronous call on the context-bound object:"); result = sampSyncObj.Square(param); Console.Write("The result of calling sampSyncObj.Square with "); Console.WriteLine("{0} is {1}.", param, result); Console.WriteLine(""); SampSyncSqrDelegate sampleDelegate = new SampSyncSqrDelegate(sampSyncObj.Square); param = 8; Console.WriteLine("Making a single asynchronous call on the context-bound object:"); IAsyncResult ar1 = sampleDelegate.BeginInvoke( param, new AsyncCallback(AsyncResultSample.MyCallback), param); Console.WriteLine("Waiting for the asynchronous call to complete..."); WaitHandle wh = ar1.AsyncWaitHandle; wh.WaitOne(); Console.WriteLine(""); Console.WriteLine("Waiting for the AsyncCallback to complete..."); Thread.Sleep(1000); } }
版權聲明: