异步调用

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Runtime.Remoting.Messaging;
 5 using System.Text;
 6 using System.Threading;
 7 
 8 namespace InvokeTest
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             Console.WriteLine("---开始同步调用---");
15             //同步调用
16             //AddHandler addHandler = new AddHandler(AddFunction);
17             //int retValue=addHandler.Invoke(20, 45);
18             //Console.WriteLine("继续做别的事情。。。");
19             //Console.WriteLine(retValue);
20             //Console.ReadKey();
21 
22             //异步调用
23             //AddHandler addHandler = new AddHandler(AddFunction);
24             //IAsyncResult result = addHandler.BeginInvoke(18,12,null,null);
25             //Console.WriteLine("继续做别的事情。。。");
26             //Console.WriteLine(addHandler.EndInvoke(result));
27             //Console.ReadKey();
28 
29             //异步回调
30             AddHandler addHandler = new AddHandler(AddFunction);
31             IAsyncResult result = addHandler.BeginInvoke(18, 12, new AsyncCallback(CallBackFunction), "回调完成");
32             Console.WriteLine("继续做别的事情。。。");
33             Console.ReadKey();
34         }
35 
36         /// <summary>
37         /// 回调方法
38         /// </summary>
39         public static void CallBackFunction(IAsyncResult result)
40         {
41             AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate;
42             Console.WriteLine(handler.EndInvoke(result));
43             Console.WriteLine(result.AsyncState);
44         }
45 
46         public delegate int AddHandler(int a,int b);
47         public static int AddFunction(int a, int b)
48         {
49             Console.WriteLine("---开始计算---");
50             Thread.Sleep(3000);
51             Console.WriteLine("---计算完成---");
52             return a + b;
53         }
54 
55     }
56 }

 

你可能感兴趣的:(异步调用)