using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ComprehensiveTest.com { public class AsyCallEx112 { // 定義一個執行加法的委托 public delegate int sum(int a, int b); public class number { public int m = 4; public int numberAdd(int a, int b) { int c = a + b; return c; } //定義一個與。net framework 定義的asyncCallback委托相對應的回調函數 public void CallbackMothed2(IAsyncResult ar2) { sum s = (sum)ar2.AsyncState; int number = s.EndInvoke(ar2); m = number; Console.WriteLine("得到的M值:{0}", m); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ComprehensiveTest.com { public class AsyCallEx113 { //定義一個委托 public delegate void AsyncEventHanlder(); public class Class1 { public void Event1() { Console.WriteLine("Event1 start"); System.Threading.Thread.Sleep(2000); Console.WriteLine("Event1 end"); } public void Event2() { Console.WriteLine("Event2 start"); int i = 1; while (i < 100) { i = i + 1; Console.WriteLine("Event2 " + i.ToString()); } Console.WriteLine("Event2 end"); } public void CallbackMethod( IAsyncResult ar ) { ((AsyncEventHanlder)ar.AsyncState).EndInvoke(ar); } } } }using System; using System.Collections.Generic; using System.Linq; using System.Text; using ComprehensiveTest.com; namespace ComprehensiveTest { class Program { static void Main(string[] args) { // 112 //AsyCallEx112.number num = new AsyCallEx112.number(); //AsyCallEx112.sum numberadd= new AsyCallEx112.sum(num.numberAdd); //AsyncCallback numberBack = new AsyncCallback(num.CallbackMothed2); //numberadd.BeginInvoke(21, 12, numberBack, numberadd); //Console.WriteLine("得到的結果:"); //Console.WriteLine(num.m); // 113 long start = 0; long end = 0; AsyCallEx113.Class1 c = new AsyCallEx113.Class1(); Console.WriteLine("ready"); start = DateTime.Now.Ticks; AsyCallEx113.AsyncEventHanlder asy = new AsyCallEx113.AsyncEventHanlder(c.Event1); //IAsyncResult ia = asy.BeginInvoke(null, null); IAsyncResult ia = asy.BeginInvoke(new AsyncCallback(c.CallbackMethod), asy); ia.AsyncWaitHandle.WaitOne(); c.Event2(); end = DateTime.Now.Ticks; Console.WriteLine("時間刻度差= " + Convert.ToString(end - start)); Console.ReadLine(); } } }