标签:
异步回调时在调用 BeginInvoke时提供的回调方法,主线程就不必再等待异步线程工作完毕,异步线程在工作结束后会主动调用提供的回调方法。
class Program
{
public delegate void PrintDelegate(string content);
static void Main(string[] args)
{
int threadId = Thread.CurrentThread.ManagedThreadId;
PrintDelegate printDelegate = new PrintDelegate(Print);
Console.WriteLine("[主线程id:{0}]\t开始调用打印的方法...", threadId);
IAsyncResult result = printDelegate.BeginInvoke("Hello Word!", PrintComplete,printDelegate);
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);
}
}
标签:
原文地址:http://www.cnblogs.com/lx4556332/p/5878040.html