csharp-async
Get best practices for C# async programming
摘要
- 用途
- 协助设计与查看 C# 异步代码,着重于 Task 的使用、例外传递与有效率的并行作业。
- 使用时机
- 撰写或查看 C# 异步方法、协调并行工作、处理取消,或处理异步串流时使用。
- 输出结果
- 它会指出异步编程的常见问题,并就方法命名、回传类型、例外处理、取消、并行作业与异步模式提出改进建议。
上游变更(7 条,最新收录 2026-02-19)
caab1f6 Convert all prompts to skills and update plugin manifests 此补丁添加 C# 异步编程最佳实务技能,涵盖命名、回传类型、例外处理、性能、常见陷阱及实作模式。 2f9c96d Fix deprecated 'mode' attribute in prompt files by renaming to 'agent' (#441) 提示的 front matter 将 `mode` 键改名为 `agent`,并保留 `'agent'` 作为其值。 2b45ca4 feat: update deprecated tool names to namespaced versions (#365) 提示的工具清单将 `codebase` 替换为 `search/codebase`。 6fb794b Update development instructions and guidelines (#29) 提示的 front matter 将 `mode`、`tools` 和 `description` 值的双引号格式改为单引号格式。 9872a77 Improving the tools for prompts 提示的工具清单从 `codebase` 和 `terminalCommand` 改为 `changes`、`codebase`、`editFiles` 和 `problems`。 4c8ad05 Initial setup of repo with prompts and instructions 初始补丁添加 C# 异步编程最佳实务提示,包含 agent 中继数据、`codebase`/`terminalCommand` 工具,以及命名、回传类型、例外、性能、陷阱和实作模式的指引。 npx skills add "lettucebo/Skills#v2.2.0@csharp-async" --full-depth ⚠ v2.2.0 发布后即可使用
C# Async Programming Best Practices
Your goal is to help me follow best practices for asynchronous programming in C#.
Naming Conventions
- Use the 'Async' suffix for all async methods
- Match method names with their synchronous counterparts when applicable (e.g.,
GetDataAsync()forGetData())
Return Types
- Return
Task<T>when the method returns a value - Return
Taskwhen the method doesn't return a value - Consider
ValueTask<T>for high-performance scenarios to reduce allocations - Avoid returning
voidfor async methods except for event handlers
Exception Handling
- Use try/catch blocks around await expressions
- Avoid swallowing exceptions in async methods
- Use
ConfigureAwait(false)when appropriate to prevent deadlocks in library code - Propagate exceptions with
Task.FromException()instead of throwing in async Task returning methods
Performance
- Use
Task.WhenAll()for parallel execution of multiple tasks - Use
Task.WhenAny()for implementing timeouts or taking the first completed task - Avoid unnecessary async/await when simply passing through task results
- Consider cancellation tokens for long-running operations
Common Pitfalls
- Never use
.Wait(),.Result, or.GetAwaiter().GetResult()in async code - Avoid mixing blocking and async code
- Don't create async void methods (except for event handlers)
- Always await Task-returning methods
Implementation Patterns
- Implement the async command pattern for long-running operations
- Use async streams (IAsyncEnumerable) for processing sequences asynchronously
- Consider the task-based asynchronous pattern (TAP) for public APIs
When reviewing my C# code, identify these issues and suggest improvements that follow these best practices.