asynChronous delegaTes 异步委托

static int TakesAWhile(int data, int ms)
{
Console.WriteLine("TakesAWhile started");
Thread.Sleep(ms);
Console.WriteLine("TakesAWhile completed");
return ++data;
}

A simple way to create a thread is by defi ning a delegate and invoking the delegate asynchronously

The delegate uses a thread pool for asynchronous tasks.

public delegate int TakesAWhileDelegate(int data, int ms);

static void Main()
{
// synchronous method call
// TakesAWhile(1, 3000);
// asynchronous by using a delegate
TakesAWhileDelegate d1 = TakesAWhile;
IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null);
while (!ar.IsCompleted)//如果委托线程没有完成
{
// doing something else in the main thread
Console.Write(".");
Thread.Sleep(50);
}
int result = d1.EndInvoke(ar);//结束委托线程
Console.WriteLine("result: {0}", result);
}

.TakesAWhile started
..TakesAWhile completed
result: 2

你可能感兴趣的:(delegate)