CCR(Concurrency and Coordination Runtime)是 .NET 平台上的異步消息傳遞庫,提供輕量級、類型安全的通道與面向 Action 的組件連接方式。其核心優勢:
taskQueue.Enqueue(Arbiter.FromHandler(() => Console.WriteLine("Hello, world.")));
var port = new Port();
Arbiter.Activate(taskQueue, port.Receive(Console.WriteLine));
port.Post("Hello (again), world");
port.Receive 創建一次性接收器;Arbiter.Activate 綁定任務隊列。關鍵點:仲裁器永不阻塞線程,無消息時線程釋放處理其他任務。
Arbiter.Activate(taskQueue, Arbiter.Receive(true, port, Console.WriteLine));
第一個參數 true 表示持久化,處理完不銷毀。多條消息並發處理時順序不保證。
static IEnumerator ProcessMessages(Port port) {
while (true) yield return port.Receive(Console.WriteLine);
}
Arbiter.Activate(taskQueue, new IterativeTask(port, ProcessMessages));
利用 C# 迭代器(yield return)實現非阻塞的順序邏輯,代碼風格接近同步調用。
yield return portSet.Choice(msg => Console.WriteLine(msg), signal => fDone = true);
Arbiter.JoinedReceive(false, port1, port2, (x, y) => Console.WriteLine(x + y));
適用於資源有限場景:請求端口 + 資源端口,僅當資源可用時處理請求。
ConcurrentReceiverGroup:讀任務並發。ExclusiveReceiverGroup:寫任務獨占,優先級高。TeardownReceiverGroup:關閉時執行清理。static IEnumerator Copy(FileStream source, FileStream target) {
var buffer = new byte[128*1024]; var port = new Port();
do {
source.BeginRead(buffer, 0, buffer.Length, port.Post, null);
yield return Arbiter.Receive(false, port, iar => bytesRead = source.EndRead(iar));
target.BeginWrite(buffer, 0, bytesRead, port.Post, null);
yield return Arbiter.Receive(false, port, iar => target.EndWrite(iar));
} while (bytesRead > 0);
}
var exceptionPort = new Port();
Arbiter.Activate(taskQueue, exceptionPort.Receive(e => { Console.ForegroundColor=ConsoleColor.Red; Console.WriteLine("Caught "+e); Console.ResetColor(); }));
Dispatcher.AddCausality(new Causality("Example", exceptionPort));
捕獲任意任務執行過程中的異常,避免顯式 try/catch 導致的代碼膨脹與線程親和性問題。
CCR 以聲明式調度約束替代顯式線程控制,讓應用自然表達數據依賴,充分利用多核資源,是構建高伸縮、高容錯系統的利器。