淺析C#非同步作業

來源:互聯網
上載者:User

這裡介紹開始C#非同步作業後如果要阻止應用程式,可以直接調用 End 方法,這會阻止應用程式直到非同步作業完成後再繼續執行。

.NET Framework 為非同步作業提供了兩種設計模式:使用 IAsyncResult 對象的非同步作業與使用事件的非同步作業。先來學習前者

概述

IAsyncResult 非同步設計模式通過名為 BeginOperationName 和 EndOperationName 的兩個方法來實現原同步方法的非同步呼叫,如 FileStream 類提供了 BeginRead 和 EndRead 方法來從檔案非同步讀取位元組,它們是 Read 方法的非同步版本

Begin 方法包含同步方法簽名中的任何參數,此外還包含另外兩個參數:一個AsyncCallback 委託和一個使用者定義的狀態物件。委託用來調用回調方法,狀態物件是用來向回調方法傳遞狀態資訊。該方法返回一個實現 IAsyncResult 介面的對象

End 方法用於結束C#非同步作業並返回結果,因此包含同步方法簽名中的 ref 和 out 參數,傳回值類型也與同步方法相同。該方法還包括一個 IAsyncResult 參數,用於擷取非同步作業是否完成的資訊,當然在使用時就必須傳入對應的 Begin 方法返回的對象執行個體

開始C#非同步作業後如果要阻止應用程式,可以直接調用 End 方法,這會阻止應用程式直到非同步作業完成後再繼續執行。也可以使用 IAsyncResult 的 AsyncWaitHandle 屬性,調用其中的WaitOne等方法來阻塞線程。這兩種方法的區別不大,只是前者必須一直等待而後者可以設定等待逾時

如果不阻止應用程式,則可以通過輪循 IAsyncResult 的 IsCompleted 狀態來判斷操作是否完成,或使用 AsyncCallback 委託來結束C#非同步作業。AsyncCallback 委託包含一個 IAsyncResult 的簽名,回調方法內部再調用 End 方法來擷取操作執行結果

嘗試

先來熟悉一下今天的主角,IAsyncResult 介面

 
  1. public interface IAsyncResult  
  2. {  
  3. object AsyncState { get; }  
  4. WaitHandle AsyncWaitHandle { get; }  
  5. bool CompletedSynchronously { get; }  
  6. bool IsCompleted { get; }  

我用一個 AsyncDemo 類作為非同步方法呼叫的提供者,後面的程式都會調用它。內部很簡單,建構函式接收一個字串作為 name ,Run 方法輸出 "My name is " + name ,而非同步方法呼叫直接用委託的 BeginInvoke 和 EndInvoke 方法實現。

 
  1. public class AsyncDemo  
  2. {  
  3. // Use in asynchronous methods  
  4. private delegate string runDelegate();  
  5. private string m_Name;  
  6. private runDelegate m_Delegate;  
  7. public AsyncDemo(string name)  
  8. {  
  9. m_Name = name;  
  10. m_Delegate = new runDelegate(Run);  
  11. }  
  12. /**////  
  13. /// Synchronous method  
  14. ///  
  15. ///  
  16. public string Run()  
  17. {  
  18. return "My name is " + m_Name;  
  19. }  
  20. /**////  
  21. /// Asynchronous begin method  
  22. ///  
  23. ///  
  24. ///  
  25. ///  
  26. public IAsyncResult BeginRun(AsyncCallback callBack, Object stateObject)  
  27. {  
  28. try  
  29. {  
  30. return m_Delegate.BeginInvoke(callBack, stateObject);  
  31. }  
  32. catch(Exception e)  
  33. {  
  34. // Hide inside method invoking stack  
  35. throw e;  
  36. }  
  37. }  
  38. /**////  
  39. /// Asynchronous end method  
  40. ///  
  41. ///  
  42. ///  
  43. public string EndRun(IAsyncResult ar)  
  44. {  
  45. if (ar == null)  
  46. throw new NullReferenceException("Arggument ar can't be null");  
  47. try  
  48. {  
  49. return m_Delegate.EndInvoke(ar);  
  50. }  
  51. catch (Exception e)  
  52. {  
  53. // Hide inside method invoking stack  
  54. throw e;  
  55. }  
  56. }  

首先是 Begin 之後直接調用 End 方法,當然中間也可以做其他的操作。

 
  1. class AsyncTest  
  2. {  
  3. static void Main(string[] args)  
  4. {  
  5. AsyncDemo demo = new AsyncDemo("jiangnii");  
  6. // Execute begin method  
  7. IAsyncResult ar = demo.BeginRun(null, null);  
  8. // You can do other things here  
  9. // Use end method to block thread until the operation is complete  
  10. string demodemoName = demo.EndRun(ar);  
  11. Console.WriteLine(demoName);  
  12. }  

也可以用 IAsyncResult 的 AsyncWaitHandle 屬性,我在這裡設定為1秒逾時。

 
  1. class AsyncTest  
  2. {  
  3. static void Main(string[] args)  
  4. {  
  5. AsyncDemo demo = new AsyncDemo("jiangnii");  
  6. // Execute begin method  
  7. IAsyncResult ar = demo.BeginRun(null, null);  
  8. // You can do other things here  
  9. // Use AsyncWaitHandle.WaitOne method to block thread for 1 second at most  
  10. ar.AsyncWaitHandle.WaitOne(1000, false);  
  11. if (ar.IsCompleted)  
  12. {  
  13. // Still need use end method to get result,   
  14. // but this time it will return immediately  
  15. string demodemoName = demo.EndRun(ar);  
  16. Console.WriteLine(demoName);  
  17. }  
  18. else  
  19. {  
  20. Console.WriteLine("Sorry, can't get demoName, the time is over");  
  21. }  
  22. }  

不中斷的輪循,每次迴圈輸出一個 "."

 
  1. class AsyncTest  
  2. {  
  3. static void Main(string[] args)  
  4. {  
  5. AsyncDemo demo = new AsyncDemo("jiangnii");  
  6. // Execute begin method  
  7. IAsyncResult ar = demo.BeginRun(null, null);  
  8. Console.Write("Waiting..");  
  9. while (!ar.IsCompleted)  
  10. {  
  11. Console.Write(".");  
  12. // You can do other things here  
  13. }  
  14. Console.WriteLine();  
  15. // Still need use end method to get result,   
  16. // but this time it will return immediately  
  17. string demodemoName = demo.EndRun(ar);  
  18. Console.WriteLine(demoName);  
  19. }  

最後是使用回調方法並加上狀態物件,狀態物件被作為 IAsyncResult 參數的 AsyncState 屬性被傳給回調方法。回調方法執行前不能讓主線程退出,我這裡只是簡單的讓其休眠了1秒。另一個與之前不同的地方是 AsyncDemo 對象被定義成了類的靜態欄位,以便回調方法使用

 
  1. class AsyncTest  
  2. {  
  3. static AsyncDemo demo = new AsyncDemo("jiangnii");  
  4. static void Main(string[] args)  
  5. {  
  6. // State object  
  7. bool state = false;  
  8. // Execute begin method  
  9. IAsyncResult ar = demo.BeginRun(new AsyncCallback(outPut), state);  
  10. // You can do other thins here  
  11. // Wait until callback finished  
  12. System.Threading.Thread.Sleep(1000);  
  13. }  
  14. // Callback method  
  15. static void outPut(IAsyncResult ar)  
  16. {  
  17. bool state = (bool)ar.AsyncState;  
  18. string demodemoName = demo.EndRun(ar);  
  19. if (state)  
  20. {  
  21. Console.WriteLine(demoName);  
  22. }  
  23. else  
  24. {  
  25. Console.WriteLine(demoName + ", isn't it?");  
  26. }  
  27. }  

C#非同步作業總結

對於一個已經實現了 BeginOperationName 和 EndOperationName 方法的對象,我們可以直接用上述方式調用,但對於只有同步方法的對象,我們要對其進行非同步呼叫也不需要增加對應的非同步方法呼叫,而只需定義一個委託並使用其 BeginInvoke 和 EndInvoke 方法就可以了

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.