委托的调用方法
- 同步调用
- 异步调用
- 异步回调
下面通过代码展示,
- 首先定义需要委托的函数
using System;
using System.Threading;
namespace BeginInvokeDemo
{
public class Calculator
{
public static int Add(int a, int b)
{
Console.WriteLine("[{0}] Begin to calc: " + a + " + " + b, TimeUtils.getCurrentTime());
Thread.Sleep(new TimeSpan(0, 0, 2));
Console.WriteLine("[{0}] Calc done!", TimeUtils.getCurrentTime());
return a + b;
}
}
}
- 为了比较好的展示,定义一个时间工具类
using System;
namespace BeginInvokeDemo
{
public class TimeUtils
{
public static string getCurrentTime()
{
//return string.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", DateTime.Now);
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
}
}
}
- 调用代码
using System;
using System.Runtime.Remoting.Messaging;
namespace BeginInvokeDemo
{
class Program
{
// BeginInvoke()方法前部分的参数是用来给调用它的委托对象所代理的那个方法传递参数,
// 最后两个参数中,第一个是用来声明回调函数的方法名,
// 第二个参数@object是 "传递额外的参数",
// 因为他本身是Object对象,我们可以传递任何对象。
public delegate int AddHandler(int a, int b);
static void Main(string[] args)
{
// 同步调用
Console.WriteLine("============ 同步调用 SyncInvoke Test =========");
AddHandler handler = new AddHandler(Calculator.Add);
int result = handler.Invoke(1, 2);
Console.WriteLine("[{0}] Continue to do other things...", TimeUtils.getCurrentTime());
Console.WriteLine(result);
// 异步调用
Console.WriteLine("\n============ 异步调用 AsyncInvoke Test =========");
AddHandler handler1 = new AddHandler(Calculator.Add);
IAsyncResult result1 = handler1.BeginInvoke(1, 2, null, null);
Console.WriteLine("[{0}] Continue to do other things...", TimeUtils.getCurrentTime());
Console.WriteLine(handler1.EndInvoke(result1));
// 异步回调
Console.WriteLine("\n====== 异步回调 AsyncInvoke callback Test =======");
AddHandler handler_async_callback = new AddHandler(Calculator.Add);
IAsyncResult result2 = handler_async_callback.BeginInvoke(1, 2, new AsyncCallback(Callback), "Result: AsyncState OK");
Console.WriteLine("[{0}] Continue to do other things...", TimeUtils.getCurrentTime());
Console.Read();
}
private static void Callback(IAsyncResult ar)
{
AddHandler handler = (AddHandler)((AsyncResult)ar).AsyncDelegate;
Console.WriteLine("[{0}] {1}", TimeUtils.getCurrentTime(), handler.EndInvoke(ar));
Console.WriteLine("[{0}] {1}", TimeUtils.getCurrentTime(), ar.AsyncState);
}
}
}
- 运行结果