public class AsyncDemo {
private delegate string RunDelegate(); // 內部委派型別
private string _name;
private RunDelegate _del;
public AsyncDemo(string name) {
_name = name;
_del = Run; // 繫結同步方法
}
// 同步版本
public string Run() => "My name is " + _name;
// 非同步 Begin 模式
public IAsyncResult BeginRun(AsyncCallback callback, object state) {
try { return _del.BeginInvoke(callback, state); }
catch (Exception e) { throw; } // 保留堆疊
}
// 非同步 End 模式
public string EndRun(IAsyncResult ar) {
if (ar == null) throw new ArgumentNullException(nameof(ar));
try { return _del.EndInvoke(ar); }
catch (Exception e) { throw; }
}
}
RunDelegate 封裝同步方法簽名_del = Run,避免重複建立委派實例BeginRun 直接轉發 BeginInvoke,EndRun 轉發 EndInvokear == null) 與例外重拋 (保留原始堆疊)後續文章將示範四種呼叫模式實戰。