需要使用的方法,委托:
static int GetSum(int n1, int n2)
{
Console.WriteLine("===================异步调用的函数GetSum中的线程Id:{0}", Thread.CurrentThread.ManagedThreadId);
int sum = 0;
for (int i = n1; i <= n2; i++)
{
sum += i;
Thread.Sleep(100);
}
Console.WriteLine("方法中输出的结果:{0}", sum);
return sum;
}
public delegate int MyDelegate(int n1, int n2);
一、正常调用Sum方法,比较耗时
MyDelegate md = new MyDelegate(GetSum);
int sum = md(1, 30);
Console.WriteLine("主方法中输出的Sum:{0}", sum);
Console.ReadKey();
二、基本使用异步委托
//1.异步调用委托
MyDelegate md = new MyDelegate(GetSum);
//开始异步调用委托
//BeginInvoke()返回值就是返回了一个对象,这个对象实现了IAsyncResult接口,并且该对象中封装了一些关于当前异步执行的委托的一些状态信息。
IAsyncResult asyncResult = md.BeginInvoke(1, 30, null, null);
for (int i = 0; i < 10; i++)
{
Console.WriteLine("主线程继续执行.." + i);
}
//调用EndInvoke会阻塞线程,等待异步委托执行完毕。拿到返回值。
int sum = md.EndInvoke(asyncResult);
Console.WriteLine("方法执行的返回值为:{0}", sum);
Console.WriteLine("主线程继续........");
三、异步委托的其他信息,引用上面开始调用委托的返回值asyncResult
//asyncResult.IsCompleted 当前线程委托有没有执行完毕
bool isEnd = asyncResult.AsyncWaitHandle.WaitOne(1000);//1000毫秒表示超时时间,如果等待了1000毫秒 线程还没有结束的话 那么这个方法会返回false 如果在1000毫秒以内线程结束了,那么这个方法会返回true
if (isEnd)
{
int res = md.EndInvoke(asyncResult);
Console.WriteLine(res);
}
四、异步委托带回调函数
//=======异步调用委托中的回调问题======================
MyDelegate md = GetSum;
//开始异步调用委托
IAsyncResult result = md.BeginInvoke(1, 30, new AsyncCallback(Callback),"Test");
Console.WriteLine("主线程继续执行。。。。。");
Console.ReadKey();
//该回调函数有系统自动调用,当指定的异步委托调用完毕后,自动调用该方法,并把BeginInvoke得到的返回值传进去
static void Callback(IAsyncResult syncResult) { Console.WriteLine("===================回调函数中的线程Id:{0}", Thread.CurrentThread.ManagedThreadId); //syncResult.AsyncState获取的就是BeginInvoke()中的最后一个参数。 Console.WriteLine("回调函数的参数:{0}", syncResult.AsyncState); //在回调函数中调用EndInvoke()方法就可以获取返回值。 //需要把接口类型转换为具体的对象 AsyncResult ar = syncResult as AsyncResult; int sum = ((MyDelegate)ar.AsyncDelegate).EndInvoke(ar); Console.WriteLine("返回值是:{0}", sum); }