日期:2014-05-18 浏览次数:21536 次
// AsynCall3.cs
// 异步调用示例: 轮询异步调用是否完成
using System;
using System.Threading;
// 定义异步调用方法的委托
// 它的签名必须与要异步调用的方法一致
public delegate int AsynComputeCaller(ulong l, out ulong factorial);
public class Factorial
{
// 计算阶乘
public ulong Compute(ulong l)
{
Thread.Sleep(80);
if (l == 1)
{
return 1;
}
else
{
return l * Compute(l - 1);
}
}
// 要异步调用的方法
// 1. 调用Factorial方法来计算阶乘,并用out参数返回
// 2. 统计计算阶乘所用的时间,并返回该值
public int AsynCompute(ulong l, out ulong factorial)
{
Console.WriteLine("开始异步方法");
DateTime startTime = DateTime.Now;
factorial = Compute(l);
TimeSpan usedTime = new TimeSpan(DateTime.Now.Ticks - startTime.Ticks);
Console.WriteLine("\n结束异步方法");
return usedTime.Milliseconds;
}
}
public class Test
{
public static void Main()
{
// 创建包含异步方法的类的实例
Factorial fact = new Factorial();
// 创建异步委托
AsynComputeCaller caller = new AsynComputeCaller(fact.AsynCompute);
// 启动异步调用
Console.WriteLine("启动异步调用");
ulong l = 30;
ulong lf;
IAsyncResult result = caller.BeginInvoke(l, out lf, null, null);
// 轮询异步方法是否结束
Console.WriteLine("主线程进行一些操作");
while (result.IsCompleted == false)