异步方法及其委托
1using System; 2using System.Threading; 3 4namespace Examples.AdvancedProgramming.AsynchronousOperations 5{ 6 public class AsyncDemo 7 { 8 // The method to be executed asynchronously. 9 public string TestMethod(int callDuration, out int threadId) 10 {11 Console.WriteLine("Test method begins.");12 Thread.Sleep(callDuration);13 threadId = Thread.CurrentThread.GetHashCode();14 return String.Format("My call time was {0}.", callDuration.ToString());15 }16 }17 // The delegate must have the same signature as the method18 // it will call asynchronously.19 public delegate string AsyncMethodCaller(int callDuration, out int threadId);20}
主调用方法
1using System; 2using System.Threading; 3 4namespace Examples.AdvancedProgramming.AsynchronousOperations 5{ 6 public class AsyncMain 7 { 8 static int threadId; 910 public static void Main() 11 {12 // The asynchronous method puts the thread id here.1314 // Create an instance of the test class.15 AsyncDemo ad = new AsyncDemo();1617 // Create the delegate.18 AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);19 20// // Initiate the asychronous call.21// IAsyncResult result = caller.BeginInvoke(3000,out threadId, null, null);2223 IAsyncResult result = caller.BeginInvoke(3000,24 out threadId, 25 new AsyncCallback(CallbackMethod),26 caller );2728 Console.WriteLine("Press Enter to close application.");29 Console.ReadLine();303132// Thread.Sleep(0);33// Console.WriteLine("Main thread {0} does some work.",34// Thread.CurrentThread.GetHashCode());35//36// // Wait for the WaitHandle to become signaled.37// result.AsyncWaitHandle.WaitOne();38//39// // Poll while simulating work.40// while(result.IsCompleted == false) 41// {42// Thread.Sleep(10);43// }44//45// // Call EndInvoke to wait for the asynchronous call to complete,46// // and to retrieve the results.47// string returnValue = caller.EndInvoke(out threadId, result);48//49// Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",50// threadId, returnValue);51// Console.ReadLine();52 }53 static void CallbackMethod(IAsyncResult ar) 54 {55 // Retrieve the delegate.56 AsyncMethodCaller caller = (AsyncMethodCaller) ar.AsyncState;5758 // Call EndInvoke to retrieve the results.59 string returnValue = caller.EndInvoke(out threadId, ar);6061 Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",62 threadId, returnValue);63 }64 }65}
当主调用线程,调用异步方法后,可以阻塞自己,也可以处理一些操作。也可以自定义异步线程的回调方法。还在学习中。。。
转载于:https://www.cnblogs.com/nanshouyong326/archive/2006/12/25/602851.html