.Net为执行异步操作提供了三中模式:
- 异步编程模型 (APM)
- 基于事件的异步模式(EAP)
- 基于任务的异步模式(TAP)
1.异步编程模型(APM)。
使用IAsyncResult设计模式的异步操作通过Begin操作和End操作两个方法实现。
在调用Begin操作后,调用线程继续执行指令,同时异步操作在另外一个线程上执行,调用线程调用End方法来获取结果。
Code:
1 namespace Examples 2 { 3 public class Progrom 4 { 5 public static void Main() 6 { 7 AsyncWorkTest work = new AsyncWorkTest(); 8 IAsyncResult result = work.BeginWork(CallBack, null); 9 Console.WriteLine("Work is begining..."); 10 string ret = work.EndWork(result); 11 Console.WriteLine(ret); 12 Console.WriteLine("Work is end..."); 13 Console.ReadKey(); 14 } 15 16 static void CallBack(object obj) 17 { 18 //do someing 19 } 20 } 21 22 public class AsyncResult : IAsyncResult 23 { 24 public AsyncResult() 25 { 26 //Accept parameters 27 } 28 private object asyncState; 29 private volatile bool isCompleted; 30 private volatile bool completedSynchronously; 31 private ManualResetEvent asynWaitHandle; 32 33 public string Result = "Mandel"; 34 35 public object AsyncState 36 { 37 get { return asyncState; } 38 } 39 public WaitHandle AsyncWaitHandle 40 { 41 get 42 { 43 if (this.asynWaitHandle == null) 44 { 45 Interlocked.CompareExchange<ManualResetEvent>(ref this.asynWaitHandle, new ManualResetEvent(false), null); 46 } 47 return asynWaitHandle; 48 } 49 } 50 public bool CompletedSynchronously 51 { 52 get { return completedSynchronously; } 53 } 54 public bool IsCompleted 55 { 56 get { return isCompleted; } 57 } 58 59 public void Work() 60 { 61 //do someing 62 Thread.Sleep(3000); ; 63 Result = "The Silent Southern Girl"; 64 asyncState = this; 65 completedSynchronously = false; 66 isCompleted = true; 67 asynWaitHandle.Set(); 68 } 69 70 } 71 72 public class AsyncWorkTest 73 { 74 public IAsyncResult BeginWork(AsyncCallback callback, object state) 75 { 76 AsyncResult result = new AsyncResult(); 77 ThreadPool.QueueUserWorkItem((action) => 78 { 79 result.Work(); 80 if (callback != null) 81 { 82 callback((AsyncResult)state); 83 } 84 }, state); 85 return result; 86 } 87 88 public string EndWork(IAsyncResult re) 89 { 90 AsyncResult result = (AsyncResult)re; 91 result.AsyncWaitHandle.WaitOne(); 92 return result.Result; 93 } 94 } 95 96 }