C# 迭代器處理非同步是並發程式挑戰之一。Microsoft 並行與協調執行階段 (CCR) 提供更通用框架,同樣支援迭代器非同步枚舉:
IEnumerator<ITask> CcrIterator(string pathname) {
var resultPort = new Port<IAsyncResult>();
using (FileStream fs = new FileStream(pathname, FileMode.Open, FileAccess.Read, FileShare.Read, 8192, FileOptions.Asynchronous)) {
Byte[] data = new Byte[fs.Length];
fs.BeginRead(data, 0, data.Length, resultPort.Post, null);
yield return resultPort;
IAsyncResult ar = resultPort;
Int32 bytesRead = fs.EndRead(ar);
}
ProcessData(data);
}
CCR 另提供異常處理與仲裁器等協調原語擴充支援。—— Howard Dierking 主編
BeginXxx(..., ae.End(), null)。yield return 1 暫停,告知需等待 1 項作業。ae.DequeueAsyncResult() 取出 IAsyncResult 傳給 EndXxx。從 Web 伺服器以 1KB 為單位讀取 HTML 並存檔(見上一節完整程式碼)。呼叫方式:
AsyncEnumerator ae = new AsyncEnumerator();
ae.Execute(HtmlToFile(ae, "https://www.Wintellect.com/", "LocalFile.Html"));
迭代器接受參數並持有 AsyncEnumerator 參考以呼叫 End/DequeueAsyncResult。