Document

简单的异步

  1. using System;  
  2. using System.Threading;  
  3. namespace ConsoleApplication1  
  4. {  
  5.     class Class1  
  6.     {  
  7.         //声明委托  
  8.         public delegate void AsyncEventHandler();  
  9.   
  10.         //异步方法  
  11.         void Event1()  
  12.         {  
  13.             Console.WriteLine("Event1 Start");  
  14.             System.Threading.Thread.Sleep(4000);  
  15.             Console.WriteLine("Event1 End");  
  16.         }  
  17.         // 同步方法  
  18.         void Event2()  
  19.         {  
  20.             Console.WriteLine("Event2 Start");  
  21.             int i = 1;  
  22.             while (i < 10)  
  23.             {  
  24.                 i = i + 1;  
  25.                 Console.WriteLine("Event2 " + i.ToString());  
  26.             }  
  27.             Console.WriteLine("Event2 End");  
  28.         }  
  29.         void Event3()   
  30.         {  
  31.             Console.WriteLine("Event3 Start");  
  32.             for (int i = 0; i < 100; i++)  
  33.             {  
  34.                 Thread.Sleep(5);  
  35.                 Console.WriteLine(i.ToString());  
  36.             }  
  37.             Console.WriteLine("Event3 End.");  
  38.         }  
  39.   
  40.         [STAThread]  
  41.         static void Main(string[] args)  
  42.         {  
  43.             long start = 0;  
  44.             long end = 0;  
  45.             Class1 c = new Class1();  
  46.             Console.WriteLine("ready");  
  47.             start = DateTime.Now.Ticks;  
  48.             //实例委托  
  49.             AsyncEventHandler asy = new AsyncEventHandler(c.Event1);  
  50.             //异步调用开始,没有回调函数和AsyncState,都为null  
  51.             IAsyncResult ia = asy.BeginInvoke(null, null);  
  52.             //同步开始,  
  53.             c.Event2();  
  54.             //异步结束,若没有结束,一直阻塞到调用完成,在此返回该函数的return,若有返回值。  
  55.   
  56.             asy.EndInvoke(ia);  
  57.             //都同步的情况。  
  58.             //c.Event1();  
  59.             //c.Event2();  
  60.   
  61.             end = DateTime.Now.Ticks;  
  62.             Console.WriteLine("时间刻度差=" + Convert.ToString(end - start));  
  63.             Console.ReadLine();  
  64.         }  
  65.     }  
  66. }  
posted @ 2016-06-27 09:19  从未被超越  阅读(258)  评论(0编辑  收藏  举报