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.