public delegate int AddHandler(int a, int b);
static int Add(int a, int b)
{
Console.WriteLine("Computing " + a + " + " + b + " ...");
Thread.Sleep(3000);
Console.WriteLine("Computing Complete.");
return a + b;
}
同步
public class Foo
{
static void Main()
{
Console.WriteLine("**********SyncInvokeTest**************");
AddHandler handler = new AddHandler(Add);
int result = handler.Invoke(1, 2);
Console.WriteLine("Do other work... ... ...");
Console.WriteLine(result);
}
}
异步
public class Foo
{
static void Main()
{
Console.WriteLine("**********AsyncInvokeTest**************");
AddHandler handler = new AddHandler(Add);
IAsyncResult result = handler.BeginInvoke(1, 2, new AsyncCallback(AddComplete), "AsycState:OK");
Console.WriteLine("Do other work... ... ...");
Console.ReadLine();
}
static void AddComplete(IAsyncResult result)
{
AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate;
Console.WriteLine(handler.EndInvoke(result));
Console.WriteLine(result.AsyncState);
}
}
委托同步与异步
最新推荐文章于 2021-12-01 16:28:22 发布