Token导航 LogoToken导航TokenDH.com
开发只读github未标认证来源可访问许可证需确认审计通过

dotnet-csharp-async-patternsdotnet csharp 异步模式

Agent Skill

dotnet-csharp-async-patterns 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

436

周安装

18

GitHub Stars

16

下载量

143
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:dotnet-csharp-async-patterns(dotnet csharp 异步模式)
来源仓库:https://github.com/wshaddix/dotnet-skills
仓库路径:skills/dotnet-csharp-async-patterns
安装命令:
npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-csharp-async-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-csharp-async-patterns

简介

该技能提供 .NET 应用中 async/await 的最佳实践指导,帮助避免常见异步编程陷阱。

  • 适用于需要编写或审查异步代码的 Codex、Claude、Cursor、Gemini CLI 等宿主环境。
  • 核心能力包括全链路异步调用、取消传播控制和常见错误识别与修复。
  • 使用时应先确认项目目标框架版本,并结合依赖注入和编码规范相关技能协同应用。
  • 安装前需检查仓库权限和维护状态,注意可能涉及代码分析和规则引用操作。

SKILL.md

dotnet-csharp-async-patterns

Async/await best practices for.NET applications. Covers correct task usage, cancellation propagation, and the most common mistakes AI agents make when generating async code.

Cross-references: [skill:dotnet-csharp-dependency-injection] for IHostedService/BackgroundService registration, [skill:dotnet-csharp-coding-standards] for Async suffix naming, [skill:dotnet-csharp-modern-patterns] for language-level features.


Core Rules

Always Async All the Way

Every method in the async call chain must be async and awaited. Mixing sync and async causes deadlocks or thread pool starvation.

// Correct: async all the way
public async Task<Order> GetOrderAsync(int id, CancellationToken ct = default)
{
    var order = await _repo.GetByIdAsync(id, ct);
    return order;
}

// WRONG: blocking on async -- causes deadlocks in ASP.NET and UI contexts
public Order GetOrder(int id)
{
    return _repo.GetByIdAsync(id).Result; // DEADLOCK RISK
}

Prefer Task and ValueTask

Return Task or Task<T> by default. Use ValueTask<T> when the method frequently completes synchronously (cache hits, buffered I/O) to avoid Task allocation.

// ValueTask: frequently synchronous completion
public ValueTask<User?> GetCachedUserAsync(int id, CancellationToken ct = default)
{
    if (_cache.TryGetValue(id, out var user))
    {
        return ValueTask.FromResult<User?>(user);
    }

    return LoadUserAsync(id, ct);
}

private async ValueTask<User?> LoadUserAsync(int id, CancellationToken ct)
{
    var user = await _repo.GetByIdAsync(id, ct);
    if (user is not null)
    {
        _cache[id] = user;
    }

    return user;
}

ValueTask rules:

  • Never await a ValueTask more than once
  • Never use .Result or .GetAwaiter().GetResult() on an incomplete ValueTask
  • If you need to await multiple times or pass it around, convert with .AsTask()

Agent Gotchas

These are the most common async mistakes AI agents make when generating C# code.

1. Blocking on Async (.Result, .Wait(), .GetAwaiter().GetResult())

// WRONG -- all of these can deadlock
var result = GetDataAsync().Result;
GetDataAsync().Wait();
var result = GetDataAsync().GetAwaiter().GetResult();

// CORRECT
var result = await GetDataAsync();

The only safe place for .GetAwaiter().GetResult() is in Main() pre-C# 7.1 or in rare infrastructure code where async is impossible (static constructors, Dispose()).

2. async void

async void methods cannot be awaited, and unhandled exceptions in them crash the process.

// WRONG -- fire-and-forget, unobserved exceptions
async void ProcessOrder(Order order)
{
    await _repo.SaveAsync(order);
}

// CORRECT
async Task ProcessOrderAsync(Order order)
{
    await _repo.SaveAsync(order);
}

The only valid use of async void is event handlers (WinForms, WPF, Blazor @onclick), where the framework requires a void return type.

3. Missing ConfigureAwait

In library code, use ConfigureAwait(false) to avoid capturing the synchronization context. In application code (ASP.NET Core, console apps), it is not needed because there is no synchronization context.

// Library code
public async Task<byte[]> ReadFileAsync(string path, CancellationToken ct = default)
{
    var bytes = await File.ReadAllBytesAsync(path, ct).ConfigureAwait(false);
    return bytes;
}

// Application code (ASP.NET Core) -- ConfigureAwait not needed
public async Task<IActionResult> GetOrder(int id, CancellationToken ct)
{
    var order = await _service.GetOrderAsync(id, ct);
    return Ok(order);
}

4. Fire-and-Forget Without Error Handling

// WRONG -- exception is silently swallowed
_ = SendEmailAsync(order);

// CORRECT -- use IHostedService or a background channel
await _backgroundQueue.EnqueueAsync(ct => SendEmailAsync(order, ct));

If fire-and-forget is truly necessary, at minimum log the exception:

_ = Task.Run(async () =>
{
    try
    {
        await SendEmailAsync(order);
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Failed to send email for order {OrderId}", order.Id);
    }
});

5. Forgetting CancellationToken

Always accept and forward CancellationToken. Never silently drop it.

// WRONG -- token not forwarded
public async Task<List<Order>> GetAllAsync(CancellationToken ct = default)
{
    return await _dbContext.Orders.ToListAsync(); // missing ct!
}

// CORRECT
public async Task<List<Order>> GetAllAsync(CancellationToken ct = default)
{
    return await _dbContext.Orders.ToListAsync(ct);
}

Cancellation Patterns

Creating Linked Tokens

Combine external cancellation with a timeout:

public async Task<Result> ProcessWithTimeoutAsync(CancellationToken ct = default)
{
    using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
    cts.CancelAfter(TimeSpan.FromSeconds(30));

    return await DoWorkAsync(cts.Token);
}

Responding to Cancellation

public async Task ProcessBatchAsync(IEnumerable<Item> items, CancellationToken ct = default)
{
    foreach (var item in items)
    {
        ct.ThrowIfCancellationRequested();
        await ProcessItemAsync(item, ct);
    }
}

Parallel Async

Task.WhenAll for Independent Operations

public async Task<Dashboard> LoadDashboardAsync(int userId, CancellationToken ct = default)
{
    var ordersTask = _orderService.GetRecentAsync(userId, ct);
    var profileTask = _profileService.GetAsync(userId, ct);
    var statsTask = _statsService.GetAsync(userId, ct);

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

    return new Dashboard(ordersTask.Result, profileTask.Result, statsTask.Result);
}

Parallel.ForEachAsync (.NET 6+) for Bounded Parallelism

await Parallel.ForEachAsync(items, new ParallelOptions
{
    MaxDegreeOfParallelism = 4,
    CancellationToken = ct
}, async (item, token) =>
{
    await ProcessItemAsync(item, token);
});

IAsyncEnumerable<T> Streaming

Use IAsyncEnumerable<T> for streaming results instead of buffering entire collections:

public async IAsyncEnumerable<Order> GetOrdersStreamAsync(
    [EnumeratorCancellation] CancellationToken ct = default)
{
    await foreach (var order in _dbContext.Orders.AsAsyncEnumerable().WithCancellation(ct))
    {
        yield return order;
    }
}

Background Work

For background processing, use BackgroundService (or IHostedService) instead of Task.Run or fire-and-forget patterns. See [skill:dotnet-csharp-dependency-injection] for registration patterns.

public sealed class OrderProcessorWorker(
    IServiceScopeFactory scopeFactory,
    ILogger<OrderProcessorWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            using var scope = scopeFactory.CreateScope();
            var processor = scope.ServiceProvider.GetRequiredService<IOrderProcessor>();

            await processor.ProcessPendingAsync(stoppingToken);
            await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
        }
    }
}

Testing Async Code

[Fact]
public async Task GetOrderAsync_WhenFound_ReturnsOrder()
{
    // Arrange
    var repo = Substitute.For<IOrderRepository>();
    repo.GetByIdAsync(42, Arg.Any<CancellationToken>())
        .Returns(new Order { Id = 42 });
    var service = new OrderService(repo);

    // Act
    var result = await service.GetOrderAsync(42);

    // Assert
    Assert.NotNull(result);
    Assert.Equal(42, result.Id);
}

[Fact]
public async Task ProcessAsync_WhenCancelled_ThrowsOperationCanceled()
{
    using var cts = new CancellationTokenSource();
    cts.Cancel();

    await Assert.ThrowsAsync<OperationCanceledException>(
        () => _service.ProcessAsync(cts.Token));
}

Knowledge Sources

Async patterns in this skill are grounded in publicly available content from:

Note: This skill applies publicly documented guidance. It does not represent or speak for the named sources.

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

33.94%
按下载量换算49

Claude

30.09%
按下载量换算43

Cursor

19.04%
按下载量换算27

Gemini CLI

8.98%
按下载量换算13

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

只读

该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills