Community编程与开发github.com

csharp-concurrency-patterns

为 .NET 选择正确的并发抽象——从异步/等待用于 I/O、通道用于生产者/消费者,到 Akka.NET 用于有状态实体管理。除非绝对必要,否则避免使用锁和手动同步。

csharp-concurrency-patterns 是什么?

此技能帮助 .NET 开发者在处理并发操作时,从简单到复杂选择最合适的抽象工具。核心哲学是“从简单开始,只在需要时升级”:大多数日常并发问题(如 I/O 等待)用 async/await 即可解决;CPU 密集型任务推荐 Parallel.ForEachAsync;生产者-消费者模式使用 System.Threading.Channels 实现背压和缓冲;UI 事件处理(如防抖、节流)适合 Reactive Extensions (Rx);服务器端流处理(批处理、节流、背压)推荐 Akka.NET Streams;复杂状态机或大量独立实体管理则用 Akka.NET Actors 的实体-角色模式。该技能强调避免共享可变状态,将锁和传统同步原语作为最后手段:优先通过不可变性、消息传递或角色隔离来设计规避锁,其次考虑 System.Collections.Concurrent 或 Channel<T> 序列化访问,仅在无法避免时使用简单的 lock 临界区。决策树和参考文件 advanced-concurrency.md 进一步覆盖了 Akka.NET Streams、Rx 和 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 来序列化访问

第1级: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)。不要阻塞异步代码。


第2级: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 操作、顺序重要、需要背压时。


第3级: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 不适合: 复杂的流操作(批处理、窗口化)、有状态的逐实体处理、复杂的监督。


第4+级: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.

相关技能