异步回调时在调用 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);
}
}