csharp-async

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

C# 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.,
    GetDataAsync()
    for
    GetData()
    )
  • 所有异步方法使用“Async”后缀
  • 适用时,方法名称与其同步对应项匹配(例如,
    GetData()
    对应的
    GetDataAsync()

Return Types

返回类型

  • Return
    Task<T>
    when the method returns a value
  • Return
    Task
    when the method doesn't return a value
  • Consider
    ValueTask<T>
    for high-performance scenarios to reduce allocations
  • Avoid returning
    void
    for async methods except for event handlers
  • 当方法返回值时,返回
    Task<T>
  • 当方法不返回值时,返回
    Task
  • 在高性能场景下考虑使用
    ValueTask<T>
    以减少内存分配
  • 除事件处理程序外,避免异步方法返回
    void

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
  • 在await表达式周围使用try/catch块
  • 避免在异步方法中吞掉异常
  • 在合适的情况下使用
    ConfigureAwait(false)
    以避免库代码中的死锁
  • 在返回async Task的方法中,使用
    Task.FromException()
    传播异常,而非直接抛出

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
  • 使用
    Task.WhenAll()
    并行执行多个任务
  • 使用
    Task.WhenAny()
    实现超时或获取第一个完成的任务
  • 当仅传递任务结果时,避免不必要的async/await
  • 对于长时间运行的操作,考虑使用取消令牌

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
  • 切勿在异步代码中使用
    .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#代码时,请识别这些问题并提出符合这些最佳实践的改进建议。