using System;using System.Text;using System.Collections.Generic;using System.Threading;namespace Test{ class Program { static int TakesAWhile(int data, int ms) { Console.WriteLine("TakesAWhile started"); Thread.Sleep(ms); Console.WriteLine("TakesAWhile completed"); return ++data; } //定义一个委托 public delegate int TakesAWhileDelegate(int data, int ms); static void Main() { TakesAWhileDelegate d1 = TakesAWhile;//声明一个委托 //BeginInvoke可以返回委托的相关信息,第三个参数null可以 //是某个函数,意味着调用完成后所执行的函数 //其实在这里委托的功能类似于线程 IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null); while (!ar.IsCompleted)//判断委托是否完成任务 { Console.Write("."); Thread.Sleep(50); } int result = d1.EndInvoke(ar); //返回委托所执行的结果 Console.WriteLine("result:{0}", result); } }}
等待句柄
static void Main() { TakesAWhileDelegate d1 = TakesAWhile;//声明一个委托 //BeginInvoke可以返回委托的相关信息,第三个参数null可以 //是某个函数,意味着调用完成后所执行的函数 //其实在这里委托的功能类似于线程 IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null); while (true) { Console.Write("."); //等待句柄,如果50毫秒内没有完成则返回false if (ar.AsyncWaitHandle.WaitOne(50, false)) { Console.WriteLine("Can get the result now"); break; } } int result = d1.EndInvoke(ar); //返回委托所执行的结果 Console.WriteLine("result:{0}", result); }
using System;using System.Text;using System.Collections.Generic;using System.Threading;namespace Test{ class Program { static int TakesAWhile(int data, int ms) { Console.WriteLine("TakesAWhile started"); Thread.Sleep(ms); Console.WriteLine("TakesAWhile completed"); return ++data; } static void TakesAWhileCompleted(IAsyncResult ar) { if (ar == null) throw new ArgumentNullException("ar"); TakesAWhileDelegate d1 = ar.AsyncState as TakesAWhileDelegate; int result = d1.EndInvoke(ar); //返回委托所执行的结果 Console.WriteLine("result:{0}", result); } //定义一个委托 public delegate int TakesAWhileDelegate(int data, int ms); static void Main() { TakesAWhileDelegate d1 = TakesAWhile;//声明一个委托 //BeginInvoke可以返回委托的相关信息,第三个参数是委托完成后所执行的函数 //最后一个参数可以在第三个参数代表的函数中通过ar.AsyncState获得 //另外,第三个参数所代表的函数的参数为IAsyncResult d1.BeginInvoke(1, 3000, TakesAWhileCompleted, d1); for (int i = 0; i < 100; i++) { Console.Write("."); Thread.Sleep(50); } } }}
//利用Lambda
using System;using System.Text;using System.Collections.Generic;using System.Threading;namespace Test{ class Program { static int TakesAWhile(int data, int ms) { Console.WriteLine("TakesAWhile started"); Thread.Sleep(ms); Console.WriteLine("TakesAWhile completed"); return ++data; } //定义一个委托 public delegate int TakesAWhileDelegate(int data, int ms); static void Main() { TakesAWhileDelegate d1 = TakesAWhile;//声明一个委托 //Lambda表达式可以直接访问该作用域外部的变量d1,此时 //不需要把一个值服务BeginInvoke最后一个参数 d1.BeginInvoke(1, 3000, ar => { int result = d1.EndInvoke(ar); Console.WriteLine("result:{0}", result); }, null); for (int i = 0; i < 100; i++) { Console.Write("."); Thread.Sleep(50); } } }}
0 0