[转载]C#异步委托的用法 .
??????? BeginInvoke方法,調用后立即返回,不等待調用結果。EndInvoke方法,用于檢索調用結果。調用BeginInvoke后可隨時調用 EndInvoke 方法;如果異步調用未完成,EndInvoke 將一直阻塞到異步調用完成。EndInvoke 的參數包括您需要異步執行的方法的 out 和 ref 參數(在 Visual Basic 中為 <Out> ByRef 和 ByRef)以及由 BeginInvoke 返回的 IAsyncResult
??????? BeginInvoke 異步方法簽名的規則是:
- 包括所有 IN 參數。
- 包括所有 OUT 參數。
- 包括所有 IN/OUT 參數。
- 包括所有 ByRef 參數。
- 將 AsyncCallback 和 AsyncState(可通過 IAsyncResult 接口的 AsyncState 屬性獲得)作為最后兩個參數。
- 返回 IAsyncResult。
??????? EndInvoke 異步方法簽名的規則是:
- 包括所有 IN/OUT 參數。
- 包括所有 OUT 參數。
- 包括所有 ByRef 參數。
- 將 IAsyncResult 作為最后一個參數。
- 從原始方法簽名返回原始返回類型。
??????? 結果對象 (IAsyncResult) 是從開始操作返回的,并且可用于獲取有關異步開始操作是否已完成的狀態。結果對象被傳遞到結束操作,該操作返回調用的最終返回值。在開始操作中可以提供可選的回調。如果提供回調,在調用結束后,將調用該回調;并且回調中的代碼可以調用結束操作。
AsyncCallback 委托
??????? AsyncCallback 委托用于指定在開始操作完成后應被調用的方法。下面是該委托的簽名,AsyncCallback 委托被作為開始操作上的第二個到最后一個參數傳遞:
??????? public delegate void AsyncCallback(IAsyncResult ar);IAsyncResult 接口??????? IAsyncResult 接口用于監視和管理異步操作。該接口是從開始操作返回的并被傳遞到結束操作,以將開始操作和結束操作相關聯。如果回調被指定為開始操作的一部分,則 AsyncResult 被傳遞到回調。以下代碼闡釋有關 IAsyncResult 接口的屬性,該接口可用于監視異步操作的狀態并獲取還可被傳遞到開始操作中的異步狀態對象:
public interface IAsyncResult
{
? Object AsyncState { get; }?????????????????????? //該屬性為BeginInvoke參數中的最后一個參數對象
? WaitHandle AsyncWaitHandle { get; }
? bool CompletedSynchronously { get; }
? bool IsCompleted { get; }???????????????????????? //該屬性判斷異步調用是否結束
}
- AsyncState
??????? 返回在開始操作方法調用中作為最后一個參數提供的對象。
- AsyncWaitHandle
??????? AsyncWaitHandle 屬性返回 WaitHandle,后者可用于執行 WaitHandle.WaitOne、WaitAny 或 WaitAll。
??????? 注意???直到 AsyncWaitHandle 屬性被讀取時,實現 IAsyncResult 的對象才需要創建 WaitHandle;執行時間由實施者決定。如果實施者創建了 WaitHandle,則實施者需要負責在適當的時候發出 WaitHandle 信號終止等待。例如,當異步調用的方法返回時,AsyncResult 將代表調用方終止等待。創建后,WaitHandle 應保持活動狀態,直到用戶調用結束異步操作的方法。此時,可以丟棄 AsyncWaitHandle 后的對象。
- CompletedSynchronously
??????? 如果開始操作調用已同步完成,則 CompletedSynchronously 屬性將被設置為 true。
- IsCompleted
??????? 在服務器已處理完調用后,IsCompleted 屬性將被設置為 true。
??????? 調用了 BeginInvoke 后,可以:
- 進行某些操作,然后調用 EndInvoke 一直阻塞到調用完成。
- 使用 IAsyncResult.AsyncWaitHandle 獲取 WaitHandle,使用它的 WaitOne 方法將執行一直阻塞到發出 WaitHandle 信號,然后調用 EndInvoke。
- 輪詢由 BeginInvoke 返回的 IAsyncResult,確定異步調用何時完成,然后調用 EndInvoke。
- 將用于回調方法的委托傳遞給 BeginInvoke。該方法在異步調用完成后在 ThreadPool 線程上執行,它可以調用 EndInvoke。
??????? 注:?始終在異步調用完成后調用 EndInvoke。
??????? 以下是關于異步委托的測試代碼:
using System;
using System.Threading;
?
public class AsyncDemo {
??? // The method to be executed asynchronously.
??? //
??? public string TestMethod(int callDuration, out int threadId) {
??????? Console.WriteLine("Test method begins.");
??????? Thread.Sleep(callDuration);
??????? threadId = AppDomain.GetCurrentThreadId();
??????? return "MyCallTime was " + callDuration.ToString();
??? }
}
?
// The delegate must have the same signature as the method
// you want to call asynchronously.
public delegate string AsyncDelegate(int callDuration, out int threadId);
?
public class AsyncMain {
??? static void Main(string[] args) {
??????? // The asynchronous method puts the thread id here.
??????? int threadId;
?
??????? // Create an instance of the test class.
??????? AsyncDemo ad = new AsyncDemo();
?
??????? // Create the delegate.
??????? AsyncDelegate dlgt = new AsyncDelegate(ad.TestMethod);
??
??????? // Initiate the asychronous call.
??????? IAsyncResult ar = dlgt.BeginInvoke(3000,
??????????? out threadId, null, null);
?
??????? Thread.Sleep(0);
??????? Console.WriteLine("Main thread {0} does some work.",
??????????? AppDomain.GetCurrentThreadId());
?
??????? // Wait for the WaitHandle to become signaled.
??????? ar.AsyncWaitHandle.WaitOne();
/*??????????????
這個是輪詢異步執行狀態
??????? // Poll while simulating work.
??????? while(ar.IsCompleted == false)
??????? {
??????????? Thread.Sleep(10);
??????? }
*/
??????? // Call EndInvoke to Wait for the asynchronous call to complete,
??????? // and to retrieve the results.
??????? string ret = dlgt.EndInvoke(out threadId, ar);
?
??????? Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, ret);
??? }
}
?
??????? 以下代碼是用回調函數執行EndInvoke方法
public class AsyncMain {
??? // Asynchronous method puts the thread id here.
??? private static int threadId;
?
??? static void Main(string[] args) {
??????? // Create an instance of the test class.
??????? AsyncDemo ad = new AsyncDemo();
?
??????? // Create the delegate.
??????? AsyncDelegate dlgt = new AsyncDelegate(ad.TestMethod);
??
??????? // Initiate the asychronous call.? Include an AsyncCallback
??????? // delegate representing the callback method, and the data
??????? // needed to call EndInvoke.
??????? IAsyncResult ar = dlgt.BeginInvoke(3000,
??????????? out threadId,
??????????? new AsyncCallback(CallbackMethod),
??????????? dlgt );
?
??????? Console.WriteLine("Press Enter to close application.");
??????? Console.ReadLine();
??? }
???
????????
??? // Callback method must have the same signature as the
??? // AsyncCallback delegate.
??? static void CallbackMethod(IAsyncResult ar) {
??????? // Retrieve the delegate.
??????? AsyncDelegate dlgt = (AsyncDelegate) ar.AsyncState;
?
??????? // Call EndInvoke to retrieve the results.
??????? string ret = dlgt.EndInvoke(out threadId, ar);
?
??????? Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, ret);
??? }
}
-----------------------------------------------------------------------
?
當進行耗時的工作時,可以使用異步委托執行。
view sourceprint?| using System; |
| using System.Collections.Generic; |
| using System.Linq; |
| using System.Text; |
| using System.Runtime.Remoting.Messaging; |
| ?? |
| namespace 線程 |
| { |
| ????class Program |
| ????{ |
| ????????delegate int facHandler(int n); |
| ????????static int Fac(int n) |
| ????????{ |
| ????????????if (n == 1) |
| ????????????????return 1;???????????? |
| ????????????System.Threading.Thread.Sleep(100);??????????? |
| ????????????return Fac(n - 1) * n; |
| ????????} |
| ?? |
| ????????static void callBack(IAsyncResult result) |
| ????????{ |
| ????????????//result是Fac()的返回值???????????? |
| ????????????//將AsyncDelegate強制轉換為用戶定義的委托。 |
| ????????????facHandler handler = (facHandler)((AsyncResult)result).AsyncDelegate; |
| ????????????Console.WriteLine("結果:" + handler.EndInvoke(result)); |
| ????????????Console.WriteLine(result.AsyncState); |
| ????????} |
| ?? |
| ????????static void Main(string[] args) |
| ????????{ |
| ????????????facHandler f = new facHandler(Fac); |
| ????????????//開異步方法開始執行 |
| ????????????IAsyncResult result = f.BeginInvoke(10, new AsyncCallback(callBack), "計算結束"); |
| ????????????Console.WriteLine("做其他事情先……"); |
| ????????????Console.Read(); |
| ????????} |
| ????} |
| } |
?
C#委托的異步調用
本文將主要通過“同步調用”、“異步調用”、“異步回調”三個示例來講解在用委托執行同一個“加法類”的時候的的區別和利弊。
首先,通過代碼定義一個委托和下面三個示例將要調用的方法:
/*添加的命名空間using?System.Threading;
using?System.Runtime.Remoting.Messaging;
*/
??? public?delegate?int?AddHandler(int?a,int?b);
????public?class?加法類
????{
????????public?static?int?Add(int?a,?int?b)
????????{
????????????Console.WriteLine("開始計算:"?+?a?+?"+"?+?b);
????????????Thread.Sleep(3000);?//模擬該方法運行三秒
????????????Console.WriteLine("計算完成!");
????????????return?a?+?b;
????????}
????}
?
?
同步調用
委托的Invoke方法用來進行同步調用。同步調用也可以叫阻塞調用,它將阻塞當前線程,然后執行調用,調用完畢后再繼續向下進行。
public?class?同步調用{
????????static?void?Main()
????????{
????????????Console.WriteLine("=====?同步調用?SyncInvokeTest?=====");
????????????AddHandler?handler?=?new?AddHandler(加法類.Add);
????????????int?result?=?handler.Invoke(1,?2);
????????????Console.WriteLine("繼續做別的事情。。。");
????????????Console.WriteLine(result);
????????????Console.ReadKey();
????????}
????????/*運行結果:
?????????=====?同步調用?SyncInvokeTest?=====
?????????開始計算:1+2
?????????計算完成!
?????????繼續做別的事情。。。
?????????3???????*/
}
同步調用會阻塞線程,如果是要調用一項繁重的工作(如大量IO操作),可能會讓程序停頓很長時間,造成糟糕的用戶體驗,這時候異步調用就很有必要了。
?
異步調用
異步調用不阻塞線程,而是把調用塞到線程池中,程序主線程或UI線程可以繼續執行。
委托的異步調用通過BeginInvoke和EndInvoke來實現。
{
????????static?void?Main()
????????{
????????????Console.WriteLine("=====?異步調用?AsyncInvokeTest?=====");
????????????AddHandler?handler?=?new?AddHandler(加法類.Add);
????????????//IAsyncResult:?異步操作接口(interface)
????????????//BeginInvoke:?委托(delegate)的一個異步方法的開始
????????????IAsyncResult?result?=?handler.BeginInvoke(1,?2,?null,?null);
????????????Console.WriteLine("繼續做別的事情。。。");
????????????//異步操作返回
????????????Console.WriteLine(handler.EndInvoke(result));
????????????Console.ReadKey();
????????}
????????/*運行結果:
?????????=====?異步調用?AsyncInvokeTest?=====
?????????繼續做別的事情。。。
?????????開始計算:1+2
?????????計算完成!
?????????3???????*/
}
可以看到,主線程并沒有等待,而是直接向下運行了。
但是問題依然存在,當主線程運行到EndInvoke時,如果這時調用沒有結束(這種情況很可能出現),這時為了等待調用結果,線程依舊會被阻塞。
?異步委托,也可以參考如下寫法:
Action<object>?action=(obj)=>method(obj);action.BeginInvoke(obj,ar=>action.EndInvoke(ar),null);
簡簡單單兩句話就可以完成一部操作。
?
異步回調
用回調函數,當調用結束時會自動調用回調函數,解決了為等待調用結果,而讓線程依舊被阻塞的局面。
public?class?異步回調{
????????static?void?Main()
????????{
????????????Console.WriteLine("=====?異步回調?AsyncInvokeTest?=====");
????????????AddHandler?handler?=?new?AddHandler(加法類.Add);
????????????//異步操作接口(注意BeginInvoke方法的不同!)
????????????IAsyncResult?result?=?handler.BeginInvoke(1,2,new?AsyncCallback(回調函數),"AsycState:OK");
????????????
????????????Console.WriteLine("繼續做別的事情。。。");
????????????Console.ReadKey();
????????}
????????static?void?回調函數(IAsyncResult?result)
????????{??????//result?是“加法類.Add()方法”的返回值
????????????//AsyncResult?是IAsyncResult接口的一個實現類,空間:System.Runtime.Remoting.Messaging
????????????//AsyncDelegate?屬性可以強制轉換為用戶定義的委托的實際類。
????????????AddHandler?handler?=?(AddHandler)((AsyncResult)result).AsyncDelegate;
????????????Console.WriteLine(handler.EndInvoke(result));
????????????Console.WriteLine(result.AsyncState);
????????}
????????/*運行結果:
????????=====?異步回調?AsyncInvokeTest?=====
????????開始計算:1+2
????????繼續做別的事情。。。
????????計算完成!
????????3
????????AsycState:OK
?????????????????*/
}
我定義的委托的類型為AddHandler,則為了訪問 AddHandler.EndInvoke,必須將異步委托強制轉換為 AddHandler??梢栽诋惒交卣{函數(類型為 AsyncCallback)中調用 MAddHandler.EndInvoke,以獲取最初提交的 AddHandler.BeginInvoke 的結果。?
?
問題:
(1)int result = handler.Invoke(1,2);
為什么Invoke的參數和返回值和AddHandler委托是一樣的呢?
答:
Invoke方法的參數很簡單,一個委托,一個參數表(可選),而Invoke方法的主要功能就是幫助你在UI線程上調用委托所指定的方法。Invoke方法首先檢查發出調用的線程(即當前線程)是不是UI線程,如果是,直接執行委托指向的方法,如果不是,它將切換到UI線程,然后執行委托指向的方法。不管當前線程是不是UI線程,Invoke都阻塞直到委托指向的方法執行完畢,然后切換回發出調用的線程(如果需要的話),返回。
所以Invoke方法的參數和返回值和調用他的委托應該是一致的。
(2)IAsyncResult result = handler.BeginInvoke(1,2,null,null);
BeginInvoke : 開始一個異步的請求,調用線程池中一個線程來執行,
返回IAsyncResult 對象(異步的核心). IAsyncResult 簡單的說,他存儲異步操作的狀態信息的一個接口,也可以用他來結束當前異步。
注意: BeginInvoke和EndInvoke必須成對調用.即使不需要返回值,但EndInvoke還是必須調用,否則可能會造成內存泄漏。
?
(3)IAsyncResult.AsyncState 屬性:
獲取用戶定義的對象,它限定或包含關于異步操作的信息。 例如:
{???
??????AddHandler?handler?=?(AddHandler)result.AsyncState;????
??????Console.WriteLine(handler.EndInvoke(result));?
??????。。。。。
}
?
總結
以上是生活随笔為你收集整理的[转载]C#异步委托的用法 .的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: STL 容器和迭代器连载6_顺序容器的操
- 下一篇: 给要学习.NET(c#语言)的新手一些学