IAsyncResult 接口由包含可异步操作的方法的类实现。它是启动异步操作的方法的返回类型,如 FileStream.BeginRead,也是结束异步操作的方法的第三个参数的类型,如 FileStream.EndRead。当异步操作完成时,IAsyncResult 对象也将传递给由 AsyncCallback 委托调用的方法。
支持 IAsyncResult 接口的对象存储异步操作的状态信息,并提供同步对象以允许线程在操作完成时终止。
有关如何使用 IAsyncResult 接口的详细说明,请参见“使用异步方式调用同步方法”主题。
using System;
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
//
// Context-Bound type with Synchronization Context Attribute
//
[Synchronization()]
public class SampleSyncronized : ContextBoundObject
{
// A method that does some work - returns the square of the given number
public int Square(int i)
{
Console.Write("SampleSyncronized.Square called. ");
Console.WriteLine("The hash of the current thread is: {0}", Thread.CurrentThread.GetHashCode());
return i*i;
}
}
//
// Async delegate used to call a method with this signature asynchronously
//
public delegate int SampSyncSqrDelegate(int i);
//Main sample class
public class AsyncResultSample
{
public static void Main()
{
int callParameter = 0;
int callResult = 0;
//Create an instance of a context-bound type SampleSynchronized
//Because SampleSynchronized is context-bound, the object sampSyncObj
//is a transparent proxy
SampleSyncronized sampSyncObj = new SampleSyncronized();
//call the method synchronously
Console.Write("Making a synchronous call on the object. ");
Console.WriteLine("The hash of the current thread is: {0}", Thread.CurrentThread.GetHashCode());
callParameter = 10;
callResult = sampSyncObj.Square(callParameter);
Console.WriteLine("Result of calling sampSyncObj.Square with {0} is {1}.\n\n", callParameter, callResult);
//call the method asynchronously
Console.Write("Making an asynchronous call on the object. ");
Console.WriteLine("The hash of the current thread is: {0}", Thread.CurrentThread.GetHashCode());
SampSyncSqrDelegate sampleDelegate = new SampSyncSqrDelegate(sampSyncObj.Square);
callParameter = 17;
IAsyncResult aResult = sampleDelegate.BeginInvoke(callParameter, null, null);
//Wait for the call to complete
aResult.AsyncWaitHandle.WaitOne();
callResult = sampleDelegate.EndInvoke(aResult);
Console.WriteLine("Result of calling sampSyncObj.Square with {0} is {1}.", callParameter, callResult);
}
}