异步委托调用(只支持单播委托)
public delegate int GetSumDelegate(int from, int to);
public delegate void MyDelegate2(string s1, int n1);
public delegate void MyDelegate1();
static int T3(int f, int t)
{
int sum = 0;
for (int i = f; i <= t; i++)
{
sum += i;
Thread.Sleep(500);
}
return sum;
}
static void T2(string s1,int n1)
{
Console.WriteLine("s1={0}",s1);
Thread.Sleep(1000);//线程休息一定时间
Console.WriteLine("n1={0}",n1);
}
static void T1()
{
Console.WriteLine("T1");
Thread.Sleep(1000);//线程休息一定时间
Console.WriteLine("T1");
}
调用无参数无返回值的委托
MyDelegate1 md = new MyDelegate1(T1);
IAsyncResult result = md.BeginInvoke(null, null);//最简单的直接开始异步调用,没有回调
md.EndInvoke(result);//如果希望等待异步委托调用结束后再继续后面的代码则在这里调用EndInvoke()函数
Console.WriteLine("ok");
Console.ReadKey();
调用带参数无返回值的委托
MyDelegate2 md2 = new MyDelegate2(T2);
md2.BeginInvoke("zhx", 18, null, null);//直接开始异步调用委托
Console.WriteLine("ok");
Console.ReadKey();
异步调用带参数,带返回值的委托
GetSumDelegate md = new GetSumDelegate(T3);
//第一种方法
md.BeginInvoke(1, 10, new AsyncCallback(ar =>
{
//回调函数的具体代码
}), "参数");
//第二种方法
md.BeginInvoke(1, 10, new AsyncCallback(Callback), "zhx");
Console.WriteLine("异步委托开始调用了");
Console.ReadKey();
回调函数
static void Callback(IAsyncResult ar)
{
//回调函数中首先把参数IAsyncResult类型转换为AsyncResult类型,方便后面的使用
AsyncResult result = ar as AsyncResult;
//获取用户在异步调用委托时传递过来的最后一个object参数
Console.WriteLine("最后一个参数:" + result.AsyncState.ToString());
//获取当前被异步调用的委托对象
GetSumDelegate currentDelegate = result.AsyncDelegate as GetSumDelegate;
//获取委托异步调用后的返回值
int sum = currentDelegate.EndInvoke(ar);
Console.WriteLine("最后的结果是:" + sum);
}
本文来自博客园,作者:NE_STOP,转载请注明原文链接:https://www.cnblogs.com/alineverstop/p/18004731