今天来总结下C#委托的异步调用的基础运用。
单线程(同步)委托调用
namespace DelegateDemo
{
class Program
{
public delegate int IntOp(int x, int y);
public static int Add(int x, int y)
{
Console.WriteLine("Add()所在线程ID{0}",Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(5000);//模拟耗时的操作
return x + y;
}
static void Main(string[] args)
{
Console.WriteLine("Main()方法所在线程ID{0}", Thread.CurrentThread.ManagedThreadId);
var dg = new IntOp(Add);
int x = 3, y = 4;
int rs = dg(x,y);
//直到Add()执行完毕,此处才开始执行
DoOtherJob();
Console.WriteLine("{0}+{1}={2}", x, y,rs);
Console.ReadLine();
}
public static void DoOtherJob()
{
Console.WriteLine("DoOtherJob()方法所在线程ID{0}", Thread.CurrentThread.ManagedThreadId);
}
}
}
这段程序有一个问题,当Add()方法在执行一系列的耗时操作时,在Add()方法之后执行的方法都不得不挂起等待。那么,我们能不能让委托在单独的线程上调用方法,以便模拟“同时”运行任务呢?
关键点:(C#编译器为IntOp委托动态生成的类定义的方法)
- public IAsyncResult BeginInvoke(int x, int y, AsyncCallback cb, object state);
- public int EndInvoke(IAsyncResult result);
我们修改Main()方法如下:<