在 WinForms/WPF 中,長時間運算 (資料庫查詢、檔案處理、網路請求) 若在 UI 執行緒執行,會導致介面凍結、無回應。非同步呼叫將工作委派給背景執行緒,UI 執行緒保持響應。本文系統講解 BeginInvoke/EndInvoke、AsyncCallback、Task/await 三種演進模式,並深入剖析「被動回收」機制。
delegate string MyDelegate(int num, out int num2);
private string LongRunningMethod(int num, out int num2)
{
Thread.Sleep(3000); // 模擬耗時操作
num2 = num * 2;
return "Hello " + num;
}
// 呼叫端
private void btnSync_Click(object sender, EventArgs e)
{
MyDelegate d = LongRunningMethod;
int outParam;
// 同步呼叫:UI 會凍結 3 秒
string result = d(10, out outParam);
MessageBox.Show(result);
}
private void btnAsync_Click(object sender, EventArgs e)
{
MyDelegate d = LongRunningMethod;
int outParam;
// 1. 啟動非同步
IAsyncResult ar = d.BeginInvoke(10, out outParam, null, null);
// 2. 這裡可以做其他事 (UI 保持響應)
// ...
// 3. 等待完成並取得結果 (阻塞直到完成)
string result = d.EndInvoke(out outParam, ar);
MessageBox.Show("非同步完成: " + result);
}
EndInvoke 若在未完成時呼叫,會阻塞呼叫執行緒 (若在 UI 執行緒呼叫,又回到凍結狀態)。IAsyncResult、out/ref 參數傳遞繁瑣。核心思想:不在主執行緒等待,而是傳入一個回呼委派,當非同步作業完成時,ThreadPool 自動呼叫該回呼,在回呼中執行 EndInvoke 並更新 UI (需 Invoke 回 UI 執行緒)。
using System;
using System.Windows.Forms;
using System.Runtime.Remoting.Messaging; // AsyncResult
public partial class MainForm : Form
{
// 1. 定義委派 (簽名需與目標方法一致)
private delegate string LongRunningDelegate(int num, out int num2);
// 2. 耗時方法
private string LongRunningMethod(int num, out int num2)
{
System.Threading.Thread.Sleep(3000); // 模擬工作
num2 = num * 2;
return "Result: " + num;
}
// 3. 回呼方法 (簽名固定: IAsyncResult)
private void CallbackMethod(IAsyncResult ar)
{
// 3.1 從 AsyncState 取回委派實例
LongRunningDelegate d = (LongRunningDelegate)((AsyncResult)ar).AsyncDelegate;
// 3.2 取得 out/ref 參數與回傳值
int outParam;
string result = d.EndInvoke(out outParam, ar);
// 3.3 更新 UI (必須透過 Invoke 回 UI 執行緒)
this.Invoke(new Action(() =>
{
MessageBox.Show("非同步完成!\nOut參數: " + outParam + "\n結果: " + result);
}));
}
// 4. 啟動非同步 (按鈕事件)
private void btnAsyncCallback_Click(object sender, EventArgs e)
{
LongRunningDelegate d = LongRunningMethod;
int dummy; // out 參數佔位,BeginInvoke 不需真實變數
// 關鍵:傳入 AsyncCallback 委派指向回呼方法
// 第二個參數 object state 可傳遞自定資料 (此處傳委派自身以便回呼取回)
IAsyncResult ar = d.BeginInvoke(42, out dummy, new AsyncCallback(CallbackMethod), d);
// UI 立即繼續響應,無阻塞
this.Text = "非同步執行中...";
}
}
| 關鍵點 | 說明 |
|---|---|
AsyncCallback 簽名 |
固定為 void MethodName(IAsyncResult ar),只能有一個參數。 |
| 傳遞上下文 | BeginInvoke(..., callback, state) 的 state 物件會回傳在 ar.AsyncState。常傳委派自身 (d) 以便回呼取回。 |
| 取回委派 | (AsyncResult)ar).AsyncDelegate 強轉為原委派型別 (需 System.Runtime.Remoting.Messaging)。 |
| EndInvoke 必呼叫 | 否則資源洩漏、執行緒不回收、.NET 執行階段最終拋出例外。必須在回呼中呼叫。 |
| UI 更新 | 回呼執行於 ThreadPool 執行緒,**必須**用 Control.Invoke/BeginInvoke 回 UI 執行緒更新控制項。 |
APM 模式已過時,現代 C# 使用 Task 與 async/await,語法同步化、例外處理自然、組合性強。
private async void btnModernAsync_Click(object sender, EventArgs e)
{
this.Text = "執行中...";
try
{
// Task.Run 將同步方法包裝為 Task,排入 ThreadPool
var result = await Task.Run(() => LongRunningMethod(42, out int outParam));
MessageBox.Show("完成: " + result + ", Out: " + outParam);
}
catch (Exception ex)
{
MessageBox.Show("錯誤: " + ex.Message);
}
finally
{
this.Text = "就緒";
}
}
// 若原方法無法修改,可用 Task.Factory.FromAsync 封裝 APM
private Task LongRunningAsync(int num)
{
LongRunningDelegate d = LongRunningMethod;
int dummy;
return Task.Factory.FromAsync(
(cb, state) => d.BeginInvoke(num, out dummy, cb, state),
ar => {
int outParam;
return d.EndInvoke(out outParam, ar);
},
null);
}
| 維度 | BeginInvoke/EndInvoke | AsyncCallback | Task/async-await |
|---|---|---|---|
| API 風格 | APM (舊) | APM + 回呼 | TAP (現代標準) |
| 程式碼可讀性 | 分散 (啟動/等待分離) | 分散 (回呼分離) | 線性、同步風格 |
| 例外處理 | 需在 EndInvoke try-catch | 需在回呼 try-catch | 自然 try-catch |
| 組合性 | 差 | 差 | 強 (WhenAll, WhenAny, ContinueWith) |
| 取消支援 | 無 | 無 | CancellationToken 內建 |
| 進度報告 | 手動實作 | 手動實作 | IProgress<T> 內建 |
| 適用場景 | 舊專案維護、.NET 2.0/3.5 | 需精細控制回呼邏輯的舊專案 | 所有新專案 (.NET 4.5+) |
ExecuteReaderAsync, HttpClient.GetAsync, Stream.ReadAsync)。Task.Run 卸載至 ThreadPool。async void (除事件處理器),改用 async Task 以便錯誤傳播與等待。CancellationToken 支援使用者取消長時間操作。Invoke/BeginInvoke 或 SynchronizationContext。.Result, .Wait())。從 BeginInvoke 到 AsyncCallback 再到 async/await,C# 非同步模式經歷了「手動管理 → 回呼地獄 → 同步化語法」的演進。新專案請直接使用 async/await;維護舊代碼時理解 APM/AsyncCallback 原理有助於安全重構。核心原則始終不變:不阻塞 UI 執行緒、正確回收資源、例外不丟失、取消可控。