关于 BeginInvoke 创建线程的一点儿发现
1 class Program 2 { 3 delegate void myD(string name); 4 public static void PrintName(string name) 5 { 6 for (int i = 1; i <= 9; i++) 7 { 8 Console.WriteLine("(No.{1}) My name is {0}", name, Thread.CurrentThread.ManagedThreadId); 9 Thread.Sleep(500); 10 } 11 } 12 public static void CallBack(IAsyncResult a) 13 { 14 Console.WriteLine("BeginInvoke方法创建的线程 No.{0} 执行完毕!",Thread.CurrentThread.ManagedThreadId); 15 } 16 static void Main(string[] args) 17 { 18 myD D = new myD(PrintName); 19 //使用BeginInvoke方法创建新的线程异步执行,该线程必须结束才会有返回结果, 20 //不然会产生阻塞,下边有 3 中方法来实现 21 //IAsyncResult IA = D.BeginInvoke("Jarno", null, null); 22 23 //①第一种方法,这种方法必须需要一个D.BeginInvoke方法执行后的返回对象 24 //D.EndInvoke(IA); 25 26 //②第二种方法,这种方法是利用 “轮询”的方式来实现 27 //while (IA.IsCompleted) 28 //{ 29 // //Console.WriteLine("BeginInvoke方法创建的线程执行完毕!"); 30 //} 31 32 //③第三种方法,这种方法是用回调的方法来实现 33 D.BeginInvoke("Jarno", CallBack, ""); 34 35 for (int i = 0; i < 5; i++) 36 { 37 Console.WriteLine("我是 No.{0} 线程!",Thread.CurrentThread.ManagedThreadId); 38 Thread.Sleep(1000); 39 } 40 41 Console.ReadKey(); 42 } 43 }
※主要是第③种方法:
1.CallBack 是 new AsyncCallback(CallBack) 的简写
2.CallBack 方法会在 D.BeginInvoke 创建的异步线程执行完毕后自动调用
AsyncCallback委托执行的时机 --- 引用在相应异步操作完成时调用的方法
[菜鸟学习笔记,老鸟勿喷]