csharp-async
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseC# Async Programming Best Practices
C# 异步编程最佳实践
Your goal is to help me follow best practices for asynchronous programming in C#.
你的目标是帮助我遵循C#异步编程的最佳实践。
Naming Conventions
命名约定
- Use the 'Async' suffix for all async methods
- Match method names with their synchronous counterparts when applicable (e.g., for
GetDataAsync())GetData()
- 所有异步方法使用“Async”后缀
- 适用时,方法名称与其同步对应项匹配(例如,对应的
GetData())GetDataAsync()
Return Types
返回类型
- Return when the method returns a value
Task<T> - Return when the method doesn't return a value
Task - Consider for high-performance scenarios to reduce allocations
ValueTask<T> - Avoid returning for async methods except for event handlers
void
- 当方法返回值时,返回
Task<T> - 当方法不返回值时,返回
Task - 在高性能场景下考虑使用以减少内存分配
ValueTask<T> - 除事件处理程序外,避免异步方法返回
void
Exception Handling
异常处理
- Use try/catch blocks around await expressions
- Avoid swallowing exceptions in async methods
- Use when appropriate to prevent deadlocks in library code
ConfigureAwait(false) - Propagate exceptions with instead of throwing in async Task returning methods
Task.FromException()
- 在await表达式周围使用try/catch块
- 避免在异步方法中吞掉异常
- 在合适的情况下使用以避免库代码中的死锁
ConfigureAwait(false) - 在返回async Task的方法中,使用传播异常,而非直接抛出
Task.FromException()
Performance
性能
- Use for parallel execution of multiple tasks
Task.WhenAll() - Use for implementing timeouts or taking the first completed task
Task.WhenAny() - Avoid unnecessary async/await when simply passing through task results
- Consider cancellation tokens for long-running operations
- 使用并行执行多个任务
Task.WhenAll() - 使用实现超时或获取第一个完成的任务
Task.WhenAny() - 当仅传递任务结果时,避免不必要的async/await
- 对于长时间运行的操作,考虑使用取消令牌
Common Pitfalls
常见陷阱
- Never use ,
.Wait(), or.Resultin async code.GetAwaiter().GetResult() - Avoid mixing blocking and async code
- Don't create async void methods (except for event handlers)
- Always await Task-returning methods
- 切勿在异步代码中使用、
.Wait()或.Result.GetAwaiter().GetResult() - 避免混合阻塞代码和异步代码
- 不要创建async void方法(事件处理程序除外)
- 始终等待返回Task的方法
Implementation Patterns
实现模式
- Implement the async command pattern for long-running operations
- Use async streams (IAsyncEnumerable<T>) 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.
- 为长时间运行的操作实现异步命令模式
- 使用异步流(IAsyncEnumerable<T>)异步处理序列
- 对于公共API,考虑基于任务的异步模式(TAP)
在审查我的C#代码时,请识别这些问题并提出符合这些最佳实践的改进建议。