[C#] 纯文本查看 复制代码 class Program
{
static void Main(string[] args)
{
//同步调用 会阻塞当前线程,一步一步进行调用
Console.WriteLine("============同步调用线程:" + Thread.CurrentThread.ManagedThreadId+"============");
AddHandler _handler01 = AddMethod.Add;
int _result01 = _handler01(1, 2);
Console.WriteLine("继续做别的事情。。。");
Console.WriteLine("同步调用结果:"+_result01);
Console.WriteLine();
//异步调用 不会阻塞当前线程,会放到线程池里
//异步调用通过BeginInvoke和EndInvoke来实现(成对应用)。
Console.WriteLine("============异步调用线程:" + Thread.CurrentThread.ManagedThreadId + "============");
AddHandler _handler02 = AddMethod.Add;
IAsyncResult _result02 = _handler02.BeginInvoke(3, 8, null, null);
Console.WriteLine("继续做别的事情。。。");
Console.WriteLine("异步调用结果:"+_handler02.EndInvoke(_result02));
Console.WriteLine();
//用回调函数,当调用结束时会自动调用回调函数,解决了为等待调用结果,而让线程依旧被阻塞的局面。
//BeginInvoke最后一个参数@object传递额外的参数
Console.WriteLine("============异步回调 线程:" + Thread.CurrentThread.ManagedThreadId + "============");
AddHandler _handler03 = AddMethod.Add;
IAsyncResult _result03 = null;
_result03 = _handler03.BeginInvoke(9, 8, (IAsyncResult _ia) => { Console.WriteLine("异步回调结果:"+_handler03.EndInvoke(_result03)); }, null);
Console.WriteLine("继续做别的事情。。。");
Console.ReadKey();
}
}
public delegate int AddHandler(int _a,int _b);
public class AddMethod
{
public static int Add(int _a, int _b)
{
Console.WriteLine("开始计算:" + _a + "+" + _b);
Thread.Sleep(3000);
Console.WriteLine("计算完成! 线程:"+Thread.CurrentThread.ManagedThreadId);
return _a + _b;
}
}
}
运行结果:
异步,委托,异步回调
|