public static void ThreadDemo() { Console.WriteLine("***** Async Delegate Invication *****"); Console.WriteLine("Main() invoked on thread {0}", Thread.CurrentThread.ManagedThreadId); Binaryop b = new Binaryop(add); IAsyncResult iftAR = b.BeginInvoke(10, 10, new AsyncCallback(AddComplete), "Thanks you for adding there numbers"); #region 轮询 //while (!iftAR.IsCompleted) //{ // Console.WriteLine("Do more work in Main()!"); // Thread.Sleep(1000); //} //while(! iftAR.AsyncWaitHandle.WaitOne(1000,true)) //{ // Console.WriteLine("Do more work in Main()!"); //} #endregion #region AsyncCallback委托,次线程调用成功触发消息 while (!isDone) { Thread.Sleep(1000); Console.WriteLine("Working......"); } #endregion //int anwer = b.EndInvoke(iftAR); //Console.WriteLine("10 + 10 is {0}", anwer); Console.ReadLine(); }
static void AddComplete(IAsyncResult itfAR) { Console.WriteLine("AddComplete() invoked on thread {0}", Thread.CurrentThread.ManagedThreadId); Console.WriteLine("Your addition is complete!"); AsyncResult ar = (AsyncResult)itfAR; Binaryop b = (Binaryop)ar.AsyncDelegate; Console.WriteLine("10 + 10 is {0}", b.EndInvoke(itfAR)); string msg = itfAR.AsyncState.ToString(); Console.WriteLine(msg); isDone = true; }