Review:
原作者雖然使用了漢字的類名,看起來十分蹩腳,但是,還是把同步調用、異步調用、異步回調的使用講解的很詳細的。原理講解的很清晰。
------
本文將主要通過“同步調用”、“異步調用”、“異步回調”三個示例來講解在用委托執行同一個“加法類”的時候的的區別和利弊。
首先,通過代碼定義一個委托和下面三個示例將要調用的方法:
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方法用來進行同步調用。同步調用也可以叫阻塞調用,它將阻塞當前線程,然后執行調用,調用完畢后再繼續向下進行。
{
static void Main()
{
Console.WriteLine("===== 同步調用 SyncInvokeTest =====");
AddHandler handler = new AddHandler(加法類.Add);
int result = handler.Invoke(1, 2);
Console.WriteLine("繼續做別的事情。。。");
Console.WriteLine(result);
Console.ReadKey();
}
}
同步調用會阻塞線程,如果是要調用一項繁重的工作(如大量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();
}
}
可以看到,主線程並沒有等待,而是直接向下運行了。
但是問題依然存在,當主線程運行到EndInvoke時,如果這時調用沒有結束(這種情況很可能出現),這時為了等待調用結果,線程依舊會被阻塞。
異步委托,也可以參考如下寫法:
action.BeginInvoke(obj,ar=>action.EndInvoke(ar),null);
簡簡單單兩句話就可以完成一部操作。
異步回調
用回調函數,當調用結束時會自動調用回調函數,解決了為等待調用結果,而讓線程依舊被阻塞的局面。
{
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);
}
}
我定義的委托的類型為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));
。。。。。
}
完整代碼如下:

using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ThreadCallback { class Program { public delegate int AddHandler(int a, int b, int c); public class AddClass { public static int Add(int a, int b, int c) { Console.WriteLine("\n開始計算:" + a + "+" + b + "+"+c); Thread.Sleep(3000); //模擬該方法運行三秒 Console.WriteLine("計算完成!"); return a + b + c; } } /// <summary> /// 同步調用 /// </summary> public class SynchronousCall { static void Main_S() { Console.WriteLine("===== 同步調用 SyncInvokeTest ====="); AddHandler handler = new AddHandler(AddClass.Add); int result = handler.Invoke(1, 2, 3); Console.WriteLine("繼續做別的事情。。。"); Console.WriteLine(result); Console.ReadKey(); } } /// <summary> /// 異步調用 /// </summary> public class AsynchronousCall { static void Main_S() { Console.WriteLine("===== 異步調用 AsyncInvokeTest ====="); AddHandler handler = new AddHandler(AddClass.Add); //IAsyncResult: 異步操作接口(interface) //BeginInvoke: 委托(delegate)的一個異步方法的開始 IAsyncResult result = handler.BeginInvoke(1, 2,3, null, null); Console.WriteLine("------繼續做別的事情。。。\n"); //異步操作返回 Console.WriteLine(handler.EndInvoke(result)); Console.ReadKey(); } } static void Main(string[] args) { Console.WriteLine("===== 異步回調 AsyncInvokeTest ====="); AddHandler handler = new AddHandler(AddClass.Add); //異步操作接口(注意BeginInvoke方法的不同!) IAsyncResult result = handler.BeginInvoke(1, 2,3, new AsyncCallback(CallbackFunc), "AsycState:OK"); Console.WriteLine("------繼續做別的事情。。。--------"); Console.ReadKey(); } static void CallbackFunc(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); } } }
【例2】轉自 多線程回調傳值例子|C#多線程回調傳值例子

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System; using System.Threading; namespace DataImportFromAccess { //聲明一個回調函數:注意傳遞的參數要與Example類中的函數參數類型一致 public delegate void ExampleCallback(int lineCount, Label lb); public class Form1{ public Form1() { InitializeComponent(); } public void CurrentNumber(int tempCurrent,Label lb) { lb.Text = tempCurrent.ToString(); } private void button1_Click(object sender, EventArgs e) { ThreadWithData twd = new ThreadWithData(1, 100,this.label1,new ExampleCallback(CurrentNumber)); Thread td = new Thread(new ThreadStart(twd.RunMethod)); td.Start(); } private void button2_Click(object sender, EventArgs e) { ThreadWithData twd = new ThreadWithData(2, 200,this.label2, new ExampleCallback(CurrentNumber)); Thread td = new Thread(new ThreadStart(twd.RunMethod)); td.Start(); } } public class ThreadWithData { private int start = 0; private int end = 0; private ExampleCallback callBack; private Label lb; public ThreadWithData(int start,int end,Label lb,ExampleCallback callBack) { this.start = start; this.end = end; this.callBack=callBack; this.lb = lb; } public void RunMethod() { for(int i=start;i<end;i++) { Thread.Sleep(1000); if (callBack != null) callBack(i,lb); } } } }
如果需要更進一步的了解,可參考:
C#中的多線程使用 -- Thread 類: 使用回調函數從一個線程中檢索數據