IAsyncResult 接口由包含可异步操作的方法的类实现。
它是启动异步操作的方法的返回类型,如 FileStream.BeginRead1,
也是结束异步操作的方法的第三个参数的类型,如 FileStream.EndRead2。
当异步操作完成时,IAsyncResult 对象也将传递给由 AsyncCallback3 委托调用的方法。
支持 IAsyncResult 接口的对象存储异步操作的状态信息,并提供同步对象以允许线程在操作完成时终止。
有关如何使用 IAsyncResult 接口的详细说明,请参见“使用异步方式调用同步方法4”主题。
下面的示例说明如何使用 IAsyncResult 来获取异步操作的返回值。
Imports System Imports System.Threading Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Contexts Imports System.Runtime.Remoting.Messaging '' Context-Bound type with Synchronization Context Attribute' <Synchronization()> Public Class SampleSyncronized Inherits ContextBoundObject ' A method that does some work - returns the square of the given number Public Function Square(ByVal i As Integer) As Integer Console.Write("SampleSyncronized.Square called. ") Console.WriteLine("The hash of the current thread is: {0}",Thread.CurrentThread.GetHashCode()) Return i * i End Function 'Square End Class 'SampleSyncronized'
' Async delegate used to call a method with this signature asynchronously' Delegate Function SampSyncSqrDelegate(ByVal i As Integer) As Integer 'Main sample class Public Class AsyncResultSample Public Shared Sub Main() Dim callParameter As Integer = 0 Dim callResult As Integer = 0 'Create an instance of a context-bound type SampleSynchronized'Because SampleSynchronized is context-bound,the object sampSyncObj 'is a transparent proxy ‘定义
Dim sampSyncObj As 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}.",callParameter,callResult) Console.WriteLine("") Console.WriteLine("") '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()) ’异步操作方法
Dim sampleDelegate As New SampSyncSqrDelegate(AddressOf sampSyncObj.Square) callParameter = 17 Dim aResult As IAsyncResult = sampleDelegate.BeginInvoke(callParameter,Nothing,Nothing) 'Wait for the call to complete aResult.AsyncWaitHandle.WaitOne() callResult = sampleDelegate.EndInvoke(aResult) Console.WriteLine("Result of calling sampSyncObj.Square with {0} is {1}.",callResult) Console.ReadLine() End Sub 'Main End Class 'AsyncResultSample