異步回調時在調用 BeginInvoke時提供的回調方法,主線程就沒必要再等待異步線程工做完畢,異步線程在工做結束後會主動調用提供的回調方法。異步
class Program線程
{string
public delegate void PrintDelegate(string content);it
static void Main(string[] args)io
{class
int threadId = Thread.CurrentThread.ManagedThreadId;thread
PrintDelegate printDelegate = new PrintDelegate(Print);方法
Console.WriteLine("[主線程id:{0}]\t開始調用打印的方法...", threadId);static
IAsyncResult result = printDelegate.BeginInvoke("Hello Word!", PrintComplete,printDelegate);co
Thread.Sleep(1000);
Console.ReadLine();
}
public static void Print(string content)
{
int threadId = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("[當前線程id:{0}]\t{1}",threadId,content);
Thread.Sleep(1000);
}
private static void PrintComplete(IAsyncResult asyResult)
{
if (null == asyResult)
{
throw new ArgumentException();
}
int threadId = Thread.CurrentThread.ManagedThreadId;
(asyResult.AsyncState as PrintDelegate).EndInvoke(asyResult);
Console.WriteLine("[當前線程id:{0}]\t打印方法調用完畢。", threadId);
}
}