class Program { private delegate int MyDel(int a); public static int MyMenthod(int a) { for (int i = 0; i < 1000; i++) { a++; } return a; } static void Main(string[] args) { var del = new MyDel(MyMenthod); Console.WriteLine("Before BeginInvoke"); IAsyncResult iar = del.BeginInvoke(5, null, null); Console.WriteLine("After BeginInvoke"); Console.WriteLine("Doing stuff"); long result = del.EndInvoke(iar); Console.WriteLine("結果為{0}",result); } }
class Program { private delegate int MyDel(int a); public static int MyMenthod(int a) { for (int i = 0; i < 1000; i++) { a++; } Thread.Sleep(3000); return a; } static void Main(string[] args) { var del = new MyDel(MyMenthod); IAsyncResult iar = del.BeginInvoke(5,null,null); Console.WriteLine("After BeginInvoke"); while (!iar.IsCompleted) { Console.WriteLine("還沒處理完"); Thread.Sleep(2000); Console.WriteLine("繼續處理其他事情"); } Console.WriteLine("異步執行完成"); long result = del.EndInvoke(iar); Console.WriteLine("結果為{0}",result); } }
class Program { private delegate int MyDel(int a); public static int MyMenthod(int a) { for (int i = 0; i < 1000; i++) { a++; } return a; } public static void CallBack(IAsyncResult iar) { AsyncResult ar = iar as AsyncResult; MyDel del = (MyDel)ar.AsyncDelegate; long r = del.EndInvoke(iar); Thread.Sleep(2000); Console.WriteLine("結果出來了,為{0}", r); } static void Main(string[] args) { var del = new MyDel(MyMenthod); Console.WriteLine("After BeginInvoke"); IAsyncResult iar= del.BeginInvoke(5, CallBack, del); Console.WriteLine("Doing More Work In Main"); Thread.Sleep(5000); } }