实际开发中,对于一些耗时较长的操作,我们往往会将其封装成异步方式调用,以加速系统响应或改善用户体验,下面是一个示例:
有一个现成的类MyMath,里面有一个Add方法:
1 public class MyMath 2 { 3 4 public int Add(int a, int b) 5 { 6 System.Threading.Thread.Sleep(5000); 7 return a + b; 8 } 9 10 }
对Add方法做下封装,对了对比,同时提供“同步调用”与"异步调用"二个版本:
1 /// 异步调用 2 /// </summary> 3 /// <param name="a"></param> 4 /// <param name="b"></param> 5 /// <param name="callBackAction"></param> 6 /// <returns></returns> 7 static void AyscAdd(int a, int b, Action<int> callBackAction) 8 { 9 Func<int> func = () => 10 { 11 return new MyMath().Add(a, b); 12 }; 13 func.BeginInvoke((ar) => 14 { 15 var result = func.EndInvoke(ar); 16 callBackAction.Invoke(result); 17 }, 18 null); 19 20 } 21 22 /// <summary> 23 /// 同步调用 24 /// </summary> 25 /// <param name="a"></param> 26 /// <param name="b"></param> 27 /// <returns></returns> 28 static int SyncAdd(int a, int b) 29 { 30 return new MyMath().Add(a, b); 31 }
最后调用验证:
1 static void Main(string[] args) 2 { 3 Console.WriteLine("同步调用开始=>"); 4 int a = SyncAdd(1, 2); 5 Console.WriteLine("同步调用结束:" + a); 6 7 Console.WriteLine("--------------------------"); 8 9 Console.WriteLine("异步调用开始=>"); 10 AyscAdd(3, 4, (result) => 11 { 12 Console.WriteLine("异步调用结果:" + result); 13 }); 14 Console.WriteLine("异步调用结束"); 15 16 Console.ReadLine(); 17 }
完整代码:
1 using System; 2 3 namespace ActionDemo 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 Console.WriteLine("同步调用开始=>"); 10 int a = SyncAdd(1, 2); 11 Console.WriteLine("同步调用结束:" + a); 12 13 Console.WriteLine("--------------------------"); 14 15 Console.WriteLine("异步调用开始=>"); 16 AyscAdd(3, 4, (result) => 17 { 18 Console.WriteLine("异步调用结果:" + result); 19 }); 20 Console.WriteLine("异步调用结束"); 21 22 Console.ReadLine(); 23 } 24 25 /// <summary> 26 /// 异步调用 27 /// </summary> 28 /// <param name="a"></param> 29 /// <param name="b"></param> 30 /// <param name="callBackAction"></param> 31 /// <returns></returns> 32 static void AyscAdd(int a, int b, Action<int> callBackAction) 33 { 34 Func<int> func = () => 35 { 36 return new MyMath().Add(a, b); 37 }; 38 func.BeginInvoke((ar) => 39 { 40 var result = func.EndInvoke(ar); 41 callBackAction.Invoke(result); 42 }, 43 null); 44 45 } 46 47 /// <summary> 48 /// 同步调用 49 /// </summary> 50 /// <param name="a"></param> 51 /// <param name="b"></param> 52 /// <returns></returns> 53 static int SyncAdd(int a, int b) 54 { 55 return new MyMath().Add(a, b); 56 } 57 } 58 59 public class MyMath 60 { 61 62 public int Add(int a, int b) 63 { 64 System.Threading.Thread.Sleep(5000); 65 return a + b; 66 } 67 68 } 69 }
输出结果如下:
同步调用开始=>
同步调用结束:3
--------------------------
异步调用开始=>
异步调用结束
异步调用结果:7
时间: 2024-11-01 12:04:34