C#异步委托的示例代码

  C#异步委托的示例代码,方便个人理解异步委托:

    1.VS新建控制台应用程序,复制下面代码:

      

 1      /// <summary>
 2         /// 定义异步委托
 3         /// </summary>
 4         public delegate void ExeDelegate();
 5         static void Main(string[] args)
 6         {
 7             Console.WriteLine("程序开始执行(⊙o⊙)…");
 8 
 9             ExeDelegate ed = new ExeDelegate(Add);
10             IAsyncResult result = ed.BeginInvoke(CallBack, "异步结束(⊙o⊙)…");
11 
12             //暂停2秒
13             Thread.Sleep(2000);
14             Console.WriteLine("程序正在运行(⊙o⊙)…");
15 
16             //暂停8秒
17             Thread.Sleep(8000);
18             Console.WriteLine("程序运行结束(⊙o⊙)…");
19         }
20 
21 
22         /// <summary>
23         /// 异步执行的方法
24         /// </summary>
25         public static void Add()
26         {
27             Thread.Sleep(6000);
28             Console.WriteLine("我是异步执行的方法(⊙o⊙)…");
29         }
30 
31 
32         /// <summary>
33         /// 异步回调函数
34         /// </summary>
35         /// <param name="result"></param>
36         public static void CallBack(IAsyncResult result)
37         {
38             ExeDelegate ed = (ExeDelegate)((AsyncResult)result).AsyncDelegate;
39             ed.EndInvoke(result);
40             Console.WriteLine(result.AsyncState);
41         }

 

posted @ 2017-12-23 23:34  取个好名字呢  阅读(282)  评论(0编辑  收藏  举报