Community程式設計與開發github.com

csharp-concurrency-patterns

在 .NET 中選擇合適的並行抽象層 – 從 I/O 用的 async/await、生產者/消費者用的 Channels,到狀態實體管理用的 Akka.NET。除非絕對必要,否則避免使用鎖定和手動同步。

csharp-concurrency-patterns 是什麼?

這個技能提供了一個完整的決策框架,幫助 .NET 開發者為不同的並行需求選用最適合的工具。它強調從最簡單的 `async/await` 開始,只有在特定需求(如平行處理、生產者/消費者模式、UI 事件組合、伺服器端串流處理或有狀態實體管理)無法被簡單方案滿足時,才逐步升級到 `Parallel.ForEachAsync`、`System.Threading.Channels`、Reactive Extensions (Rx) 或 Akka.NET(包含 Streams 與 Actors)。核心哲學是「避免共享的可變狀態」:優先透過不可變資料、訊息傳遞或 Actor 隔離來消除並行問題,並將鎖定視為最後手段。文件包含了詳細的決策樹、各層級的程式碼範例、常見反模式(如鎖定業務邏輯、手動執行緒管理、在非同步程式碼中阻塞)以及一份快速對照表,方便開發者快速選取正確的工具。此技能適合任何使用 .NET 進行並行程式設計的開發人員,無論是初學者或進階使用者都能從中獲得明確指導。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/csharp-concurrency-patterns

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

.NET 並行:選擇正確的工具

何時使用此技能

在以下情況使用此技能:

  • 決定如何在 .NET 中處理並行操作
  • 評估是否使用 async/await、Channels、Akka.NET 或其他抽象層
  • 想要使用鎖、號誌或其他同步原始物件時
  • 需要使用背壓、批次或去抖動來處理資料串流
  • 跨多個並行實體管理狀態

參考檔案

  • advanced-concurrency.md:Akka.NET Streams、Reactive Extensions、Akka.NET Actors(每個 Actor 對應一個實體、狀態機、叢集分片)以及非同步區域函式模式

核心哲學

從簡單開始,只在需要時升級。

大多數並行問題都可以用 async/await 解決。唯有當你有特定需求且 async/await 無法乾淨處理時,才需要更複雜的工具。

盡量避免共享的可變狀態。 處理並行的最佳方式是設計上就避免它。不可變資料、訊息傳遞和隔離狀態(如 Actor)能消除一整類的錯誤。

鎖應該是例外,而不是常態。 當你無法避免共享的可變狀態時:

  1. 第一選擇: 重新設計以避免共享(不可變性、訊息傳遞、Actor 隔離)
  2. 第二選擇: 使用 System.Collections.Concurrent(如 ConcurrentDictionary)
  3. 第三選擇: 使用 Channel<T> 透過訊息傳遞序列化存取
  4. 最後手段: 對簡單、短暫的關鍵區段使用 lock

決策樹

你想做什麼?
│
├─► 等待 I/O(HTTP、資料庫、檔案)?
│   └─► 使用 async/await
│
├─► 平行處理集合(CPU 密集型)?
│   └─► 使用 Parallel.ForEachAsync
│
├─► 生產者/消費者模式(工作佇列)?
│   └─► 使用 System.Threading.Channels
│
├─► UI 事件處理(去抖、節流、合併)?
│   └─► 使用 Reactive Extensions (Rx)
│
├─► 伺服器端串流處理(背壓、批次)?
│   └─► 使用 Akka.NET Streams
│
├─► 具有複雜轉換的狀態機?
│   └─► 使用 Akka.NET Actors(Become 模式)
│
├─► 管理許多獨立實體的狀態?
│   └─► 使用 Akka.NET Actors(每個 Actor 對應一個實體)
│
├─► 協調多個非同步操作?
│   └─► 使用 Task.WhenAll / Task.WhenAny
│
└─► 以上都不符合?
    └─► 問自己:「我真的需要共享的可變狀態嗎?」
        ├─► 是 → 考慮重新設計以避免它
        └─► 真的無法避免 → 使用 Channels 或 Actors 來序列化存取

第一級:async/await(預設選擇)

用於: I/O 綁定操作、非阻塞等待、大多數日常並行程式。

// 簡單的非同步 I/O
public async Task<Order> GetOrderAsync(string orderId, CancellationToken ct)
{
    var order = await _database.GetAsync(orderId, ct);
    var customer = await _customerService.GetAsync(order.CustomerId, ct);
    return order with { Customer = customer };
}

// 平行非同步操作(當它們彼此獨立時)
public async Task<Dashboard> LoadDashboardAsync(string userId, CancellationToken ct)
{
    var ordersTask = _orderService.GetRecentOrdersAsync(userId, ct);
    var notificationsTask = _notificationService.GetUnreadAsync(userId, ct);
    var statsTask = _statsService.GetUserStatsAsync(userId, ct);

    await Task.WhenAll(ordersTask, notificationsTask, statsTask);

    return new Dashboard(
        Orders: await ordersTask,
        Notifications: await notificationsTask,
        Stats: await statsTask);
}

關鍵原則: 永遠接受 CancellationToken。在函式庫程式碼中使用 ConfigureAwait(false)。不要在非同步程式碼上阻塞。


第二級:Parallel.ForEachAsync(CPU 密集型平行處理)

用於: 當工作為 CPU 密集型或需要控制並行度時,平行處理集合。

public async Task ProcessOrdersAsync(
    IEnumerable<Order> orders,
    CancellationToken ct)
{
    await Parallel.ForEachAsync(
        orders,
        new ParallelOptions
        {
            MaxDegreeOfParallelism = Environment.ProcessorCount,
            CancellationToken = ct
        },
        async (order, token) =>
        {
            await ProcessOrderAsync(order, token);
        });
}

何時不要使用: 純 I/O 操作、順序重要時、需要背壓時。


第三級:System.Threading.Channels(生產者/消費者)

用於: 工作佇列、生產者/消費者模式、將生產者與消費者解耦。

public class OrderProcessor
{
    private readonly Channel<Order> _channel;

    public OrderProcessor()
    {
        _channel = Channel.CreateBounded<Order>(new BoundedChannelOptions(100)
        {
            FullMode = BoundedChannelFullMode.Wait
        });
    }

    // 生產者
    public async Task EnqueueOrderAsync(Order order, CancellationToken ct)
    {
        await _channel.Writer.WriteAsync(order, ct);
    }

    // 消費者(作為背景工作執行)
    public async Task ProcessOrdersAsync(CancellationToken ct)
    {
        await foreach (var order in _channel.Reader.ReadAllAsync(ct))
        {
            await ProcessOrderAsync(order, ct);
        }
    }

    public void Complete() => _channel.Writer.Complete();
}

Channels 適合用於: 速度解耦、帶背壓的緩衝、扇出給多個工作者、背景佇列。

Channels 不適合用於: 複雜的串流操作(批次、視窗化)、每個實體的狀態處理、進階的監督機制。


第四級以上:Akka.NET Streams、Reactive Extensions、Actors

對於需要串流處理、UI 事件組合或有狀態實體管理的高階場景,請參閱 advanced-concurrency.md。

Akka.NET Streams 擅長伺服器端的批次、節流和背壓。Reactive Extensions 非常適合 UI 事件組合。Akka.NET Actors 處理每個 Actor 對應一個實體的模式、搭配 Become() 的狀態機,以及透過叢集分片的分散式系統。


反模式:應避免的做法

對業務邏輯使用鎖

// 不好:使用鎖來保護共享狀態
private readonly object _lock = new();
private Dictionary<string, Order> _orders = new();

public void UpdateOrder(string id, Action<Order> update)
{
    lock (_lock) { if (_orders.TryGetValue(id, out var order)) update(order); }
}

// 好:使用 Actor 或 Channel 來序列化存取

手動執行緒管理

// 不好:手動建立執行緒
var thread = new Thread(() => ProcessOrders());
thread.Start();

// 好:使用 Task.Run 或更好的抽象層
_ = Task.Run(() => ProcessOrdersAsync(cancellationToken));

在非同步程式碼中阻塞

// 不好:阻塞非同步程式碼 – 有死結風險!
var result = GetDataAsync().Result;

// 好:一路非同步到底
var result = await GetDataAsync();

未保護的共享可變狀態

// 不好:多個工作任務修改共享狀態
var results = new List<Result>();
await Parallel.ForEachAsync(items, async (item, ct) =>
{
    var result = await ProcessAsync(item, ct);
    results.Add(result); // 競爭條件!
});

// 好:使用 ConcurrentBag
var results = new ConcurrentBag<Result>();

快速參考:何時使用哪種工具?

需求工具範例
等待 I/Oasync/awaitHTTP 呼叫、資料庫查詢
平行 CPU 工作Parallel.ForEachAsync圖片處理、計算
工作佇列Channel<T>背景工作處理
帶去抖/節流的 UI 事件Reactive Extensions即時搜尋、自動儲存
伺服器端批次/節流Akka.NET Streams事件聚合、速率限制
狀態機Akka.NET Actors付款流程、訂單生命週期
實體狀態管理Akka.NET Actors訂單管理、使用者工作階段
觸發多個非同步操作Task.WhenAll載入儀表板資料
競速多個非同步操作Task.WhenAny超時備援
定期工作PeriodicTimer健康檢查、輪詢

升級路徑

async/await(從這裡開始)
    │
    ├─► 需要平行處理? → Parallel.ForEachAsync
    │
    ├─► 需要生產者/消費者? → Channel<T>
    │
    ├─► 需要 UI 事件組合? → Reactive Extensions
    │
    ├─► 需要伺服器端串流處理? → Akka.NET Streams
    │
    └─► 需要狀態機或實體管理? → Akka.NET Actors

只在有具體需求時才升級。 不要「以防萬一」就使用 Actors 或串流。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

相關技能