/*
线程,任务,同步之异步回调
*/
using System;
using System.Threading;
using System.Diagnostics;
namespace Frank
{
public class Test
{
public delegate int TakesAWhileDelegate(int data,int ms);
//程序入口
public static void Main(string[] args)
{
TakesAWhileDelegate dl = new TakesAWhileDelegate(TakesAWhile);
//IAsyncResult ar = dl.BeginInvoke(1,3000,TakesAWhileCompleted,null);//异步执行
//Lambda表达式
dl.BeginInvoke(1,3000,ar=>{int result = dl.EndInvoke(ar);Console.WriteLine("result:{0}",result);},null);
for(int i =0;i<100;i++)
{
Console.Write(".");
Thread.Sleep(50);
}
}
static int TakesAWhile(int data,int ms)
{
Console.WriteLine("TakesAWhile started");
Thread.Sleep(ms);
Console.WriteLine("TakesAWhile completed");
return ++data;
}
///<summary>
/// 回调函数
///</summary>
static void TakesAWhileCompleted(IAsyncResult ar)
{
if(ar == null)
{
throw new ArgumentNullException("ar");
}
TakesAWhileDelegate d1 = ar.AsyncState as TakesAWhileDelegate;
Trace.Assert(d1!=null,"Invalid object type");
int result = d1.EndInvoke(ar);
Console.WriteLine("result:{0}",result);
}
}
}