public delegate int AddHandler(int a, int b);
public class JiaFa
{
public static int Add(int a, int b)
{
Console.WriteLine("开始计算:" + a + "+" + b);
Thread.Sleep(3000);
Console.WriteLine("计算完成");
return a + b;
}
}
同步调用
static void Main1(string[] args)
{
//方式1
AddHandler handler = new AddHandler(JiaFa.Add);
var res = handler.Invoke(3, 5);
Console.WriteLine("继续做其他事情");
Console.WriteLine(res);
//方式2
//AddHandler handler2 = new AddHandler((int a, int b) =>
//{
// Console.WriteLine("开始计算:" + a + "+" + b);
// Thread.Sleep(3000);
// Console.WriteLine("计算完成");
// return a + b;
//});
//Console.WriteLine(handler2(3, 5));
Console.ReadKey();
}
异步调用
static void Main2(string[] args)
{
AddHandler handler = new AddHandler(JiaFa.Add);
IAsyncResult result = handler.BeginInvoke(3, 5, null, null);
Console.WriteLine("继续做其他事情1");
//当主线程执行到EndInvoke时,如子线程还没有执行完,则主线程还是需要等待
Console.WriteLine(handler.EndInvoke(result));
Console.WriteLine("继续做其他事情2");
Console.ReadKey();
}
异步回调
static void Main(string[] args)
{
AddHandler handler = new AddHandler(JiaFa.Add);
IAsyncResult result = handler.BeginInvoke(3, 5, new AsyncCallback(Call), "AsycState:OK");
Console.WriteLine("继续做其他事情");
Console.ReadKey();
}
static void Call(IAsyncResult result)
{
AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate;
Console.WriteLine(handler.EndInvoke(result));
Console.WriteLine(result.AsyncState);
}
原文地址:https://www.cnblogs.com/yinchh/p/10498770.html
时间: 2024-10-10 15:17:37