讓我們看一個更加復雜的例子:
public static void test4()
{
int a = 12;
int y = 32;
TheEvent ev2 = delegate(ref int x)
{ Console.WriteLine("output x + y : {0}", x + y); Thread.Sleep(100); };
//ev2(ref a);
IAsyncResult ar = ev2.BeginInvoke(ref a,
delegate(IAsyncResult ar2)
{Console.Write("Operation finished: {0} on thread ID:{1}, is pool: {2}",ar2.IsCompleted,Thread.CurrentThread.GetHashCode(), Thread.CurrentThread.IsThreadPoolThread);}
, null);
Console.WriteLine("do some other calculations while counter thread is working");
Console.Write("work status : {0} Main Thread ID:{1}, is pool: {2}",
ar.IsCompleted,
Thread.CurrentThread.GetHashCode(),
Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(500);
ev2.EndInvoke(ref a, ar);
}
這個例子中使用了系統線程池對於任務進行排隊,適合於IO或者計算密集型的操作的時候。使用匿名委托最大的好處在於可以完整地克隆當前運行空間上下文的可用變量,雖然這可能從另一個層面上也增加了同步的復雜度,所謂有得必有失。