文章来源:http://blog.csdn.net/wanlong360599336/article/details/8781477
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace ConsoleApplication1
{
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("计算完成!");
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("===== 同步调用 SyncInvokeTest =====");
AddHandler handler = new AddHandler(AddMethod.Add);
int result=handler.Invoke(1,2);
Console.WriteLine("继续做别的事情。。。");
Console.WriteLine(result);
Console.ReadKey();
Console.WriteLine("===== 异步调用 AsyncInvokeTest =====");
AddHandler handler1 = new AddHandler(AddMethod.Add);
IAsyncResult result1=handler1.BeginInvoke(1,2,null,null);
Console.WriteLine("继续做别的事情。。。");
Console.WriteLine(handler1.EndInvoke(result1));
Console.ReadKey();
Console.WriteLine("===== 异步回调 AsyncInvokeTest =====");
AddHandler handler2 = new AddHandler(AddMethod.Add);
IAsyncResult result2 = handler2.BeginInvoke(1, 2, new AsyncCallback(Callback), null);
Console.WriteLine("继续做别的事情。。。");
Console.ReadKey();
}
static void Callback(IAsyncResult result)
{
AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate;
Console.WriteLine(handler.EndInvoke(result));
}
}
}