- using System;
- using System.Threading;
- namespace ConsoleApplication1
- {
- class Class1
- {
- //声明委托
- public delegate void AsyncEventHandler();
- //异步方法
- void Event1()
- {
- Console.WriteLine("Event1 Start");
- System.Threading.Thread.Sleep(4000);
- Console.WriteLine("Event1 End");
- }
- // 同步方法
- void Event2()
- {
- Console.WriteLine("Event2 Start");
- int i = 1;
- while (i < 10)
- {
- i = i + 1;
- Console.WriteLine("Event2 " + i.ToString());
- }
- Console.WriteLine("Event2 End");
- }
- void Event3()
- {
- Console.WriteLine("Event3 Start");
- for (int i = 0; i < 100; i++)
- {
- Thread.Sleep(5);
- Console.WriteLine(i.ToString());
- }
- Console.WriteLine("Event3 End.");
- }
- [STAThread]
- static void Main(string[] args)
- {
- long start = 0;
- long end = 0;
- Class1 c = new Class1();
- Console.WriteLine("ready");
- start = DateTime.Now.Ticks;
- //实例委托
- AsyncEventHandler asy = new AsyncEventHandler(c.Event1);
- //异步调用开始,没有回调函数和AsyncState,都为null
- IAsyncResult ia = asy.BeginInvoke(null, null);
- //同步开始,
- c.Event2();
- //异步结束,若没有结束,一直阻塞到调用完成,在此返回该函数的return,若有返回值。
- asy.EndInvoke(ia);
- //都同步的情况。
- //c.Event1();
- //c.Event2();
- end = DateTime.Now.Ticks;
- Console.WriteLine("时间刻度差=" + Convert.ToString(end - start));
- Console.ReadLine();
- }
- }
- }
时间: 2024-10-12 22:50:07