async-drop

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AsyncDrop Pattern Guide

AsyncDrop 模式指南

The AsyncDrop pattern enables async cleanup for types that hold resources requiring asynchronous teardown (network connections, file handles, background tasks, etc.).
AsyncDrop 模式可为持有需要异步销毁资源(网络连接、文件句柄、后台任务等)的类型提供异步清理能力。

Core Concept

核心概念

Rust's
Drop
trait is synchronous, but sometimes cleanup needs to be async. The AsyncDrop pattern solves this by:
  1. Wrapping values in
    AsyncDropGuard<T>
  2. Requiring explicit
    async_drop().await
    calls
  3. Panicking if cleanup is forgotten
Rust 的
Drop
trait 是同步的,但有时候清理操作需要是异步的。AsyncDrop 模式通过以下方式解决该问题:
  1. 将值封装在
    AsyncDropGuard<T>
  2. 要求显式调用
    async_drop().await
  3. 如果忘记执行清理则触发 panic

Quick Reference

快速参考

rust
// Creating
let mut guard = AsyncDropGuard::new(my_value);

// Using (transparent via Deref)
guard.do_something();

// Cleanup (REQUIRED before dropping)
guard.async_drop().await?;
rust
// 创建实例
let mut guard = AsyncDropGuard::new(my_value);

// 使用(通过 Deref 透明访问)
guard.do_something();

// 清理(销毁前必须调用)
guard.async_drop().await?;

The AsyncDrop Trait

AsyncDrop Trait

rust
#[async_trait]
pub trait AsyncDrop {
    type Error: Debug;
    async fn async_drop_impl(&mut self) -> Result<(), Self::Error>;
}
rust
#[async_trait]
pub trait AsyncDrop {
    type Error: Debug;
    async fn async_drop_impl(&mut self) -> Result<(), Self::Error>;
}

Essential Rules

核心规则

RuleDescription
Always call async_drop()Every
AsyncDropGuard
must have
async_drop()
called
Factory methods return guards
fn new() -> AsyncDropGuard<Self>
, never plain
Self
Types with guard members impl AsyncDropDelegate to member async_drops
Use the macro when possible
with_async_drop_2!
handles cleanup automatically
Panics are exceptionsIt's OK to skip async_drop on panic paths
规则说明
始终调用 async_drop()每个
AsyncDropGuard
都必须调用
async_drop()
工厂方法返回 guard
fn new() -> AsyncDropGuard<Self>
,永远不要直接返回原生
Self
包含 guard 成员的类型需实现 AsyncDrop委托给成员的 async_drop 方法执行清理
尽可能使用宏
with_async_drop_2!
可自动处理清理逻辑
Panic 场景属于例外在发生 panic 的路径上可以跳过调用 async_drop

The
with_async_drop_2!
Macro

with_async_drop_2!

Automatically calls
async_drop()
on scope exit:
rust
let resource = get_resource().await?;
with_async_drop_2!(resource, {
    // Use resource here
    resource.do_work().await?;
    Ok(result)
})
在作用域退出时自动调用
async_drop()
rust
let resource = get_resource().await?;
with_async_drop_2!(resource, {
    // 在此处使用 resource
    resource.do_work().await?;
    Ok(result)
})

Additional References

额外参考

  • patterns.md - Implementation patterns and examples
  • gotchas.md - Common mistakes and how to avoid them
  • helpers.md - Helper types (AsyncDropArc, AsyncDropHashMap, etc.)
  • patterns.md - 实现模式与示例
  • gotchas.md - 常见错误与规避方案
  • helpers.md - 辅助类型(AsyncDropArc、AsyncDropHashMap 等)

Location

实现位置

Implementation:
crates/utils/src/async_drop/
实现代码位于:
crates/utils/src/async_drop/