static int TakesAWhile(int data, int ms) { Console.WriteLine("TakesAWhile started"); Thread.Sleep(ms); Console.WriteLine("TakesAWhile completed"); return ++data; } public delegate int TakesAWhileDelegate(int data, int ms); static void Main(string[] args) { TakesAWhileDelegate d1 = TakesAWhile; // polling IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null); while (!ar.IsCompleted) { // doing something else Console.Write("."); Thread.Sleep(500); } int result = d1.EndInvoke(ar); Console.WriteLine("result: {0}", result); Console.Read(); }
结果:
二:
static int TakesAWhile(int data, int ms) { Console.WriteLine("TakesAWhile started"); Thread.Sleep(ms); Console.WriteLine("TakesAWhile completed"); return ++data; } public delegate int TakesAWhileDelegate(int data, int ms); static void Main(string[] args) { TakesAWhileDelegate d1 = TakesAWhile; // wait handle IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null); while (true) { Console.Write("."); if (ar.AsyncWaitHandle.WaitOne(500, false)) { Console.WriteLine("Can get the result now"); break; } } int result = d1.EndInvoke(ar); Console.WriteLine("result: {0}", result); Console.Read(); }
结果:
三:
static int TakesAWhile(int data, int ms) { Console.WriteLine("TakesAWhile started"); Thread.Sleep(ms); Console.WriteLine("TakesAWhile completed"); return ++data; } public delegate int TakesAWhileDelegate(int data, int ms); static void Main(string[] args) { TakesAWhileDelegate d1 = TakesAWhile; // async callback d1.BeginInvoke(1, 3000, TakesAWhileCompleted, d1); for (int i = 0; i < 100; i++) { Console.Write("."); Thread.Sleep(500); } Console.Read(); } static void TakesAWhileCompleted(IAsyncResult ar) { if (ar == null) throw new ArgumentNullException("ar"); TakesAWhileDelegate d1 = ar.AsyncState as TakesAWhileDelegate; Trace.Assert(d1 != null, "Invalid object type"); int result = d1.EndInvoke(ar); Console.WriteLine("result: {0}", result); }
结果:
四:
static int TakesAWhile(int data, int ms) { Console.WriteLine("TakesAWhile started"); Thread.Sleep(ms); Console.WriteLine("TakesAWhile completed"); return ++data; } public delegate int TakesAWhileDelegate(int data, int ms); static void Main(string[] args) { TakesAWhileDelegate d1 = TakesAWhile; d1.BeginInvoke(1, 3000, ar => { int result = d1.EndInvoke(ar); Console.WriteLine("result: {0}", result); }, null); for (int i = 0; i < 100; i++) { Console.Write("."); Thread.Sleep(500); } Console.Read(); }
结果:同三