基于委托的异步回调
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于委托的异步回调相关的知识,希望对你有一定的参考价值。
异步回调时在调用 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);
}
}
以上是关于基于委托的异步回调的主要内容,如果未能解决你的问题,请参考以下文章
异步使用委托delegate --- BeginInvoke和EndInvoke方法
异步和多线程,委托异步调用,Thread,ThreadPool,Task,Parallel,CancellationTokenSource