异步委托的简单方式
#region 异步委托 简单的方式
Func<
int,
int,
string> delFunc = (a, b) =>
{
Console.WriteLine("Delegate Thread:" +
Thread.CurrentThread.ManagedThreadId);
return (a+
b).ToString();
};
//拿到异步委托的结果
IAsyncResult result = delFunc.BeginInvoke(
3,
4,
null,
null);
string str =
delFunc.EndInvoke(result);//EndInvoke方法会阻塞当前线程,直到异步委托指向完成之后才往下执行
Console.WriteLine(str);
Console.ReadKey();
#endregion
有回调函数的异步委托
#region 有回调函数的异步委托
//先写一个有返回值的委托实例
Func<
int,
int,
string> delFunc = (a, b) =>
{
return (a +
b).ToString();
};
delFunc.BeginInvoke(5,
6, MyAsyncCallback,
"123");
//在下面生成MyAsyncCallback()方法
Console.ReadKey();
}
public static void MyAsyncCallback(IAsyncResult ar)
{
//拿到异步委托的结果
AsyncResult result = (AsyncResult)ar;
//强转成子类的类型
var del = (Func<
int,
int,
string>)result.AsyncDelegate;
//result.AsyncDelegate直接指向了委托实例delFunc
string returnValue=
del.EndInvoke(result);
Console.WriteLine("返回值是" +
returnValue);
//拿到回调函数的参数
Console.WriteLine(
"回调函数的线程ID是:" +
Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("回调函数的参数是:"+
result.AsyncState);
}
#endregion
有回调函数的异步委托的另一种方法是 直接在回调函数中将委托作为参数
//另一种方法
Func<
int,
int,
string> delFunc = (a, b) =>
{
return (a +
b).ToString();
};
delFunc.BeginInvoke(5,
6, MyAsyncCallback,delFunc );
//在下面生成MyAsyncCallback()方法,直接将委托作为参数
Console.ReadKey();
}
private static void MyAsyncCallback(IAsyncResult ar)
{
var del = (Func<
int,
int,
string>
)ar.AsyncState;
string str =
del.EndInvoke(ar);
}
转载于:https://www.cnblogs.com/xiaoyaohan/p/9755672.html
相关资源:C# 异步委托 四步走