async-drop
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAsyncDrop 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 trait is synchronous, but sometimes cleanup needs to be async. The AsyncDrop pattern solves this by:
Drop- Wrapping values in
AsyncDropGuard<T> - Requiring explicit calls
async_drop().await - Panicking if cleanup is forgotten
Rust 的 trait 是同步的,但有时候清理操作需要是异步的。AsyncDrop 模式通过以下方式解决该问题:
Drop- 将值封装在 中
AsyncDropGuard<T> - 要求显式调用
async_drop().await - 如果忘记执行清理则触发 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
核心规则
| Rule | Description |
|---|---|
| Always call async_drop() | Every |
| Factory methods return guards | |
| Types with guard members impl AsyncDrop | Delegate to member async_drops |
| Use the macro when possible | |
| Panics are exceptions | It's OK to skip async_drop on panic paths |
| 规则 | 说明 |
|---|---|
| 始终调用 async_drop() | 每个 |
| 工厂方法返回 guard | |
| 包含 guard 成员的类型需实现 AsyncDrop | 委托给成员的 async_drop 方法执行清理 |
| 尽可能使用宏 | |
| Panic 场景属于例外 | 在发生 panic 的路径上可以跳过调用 async_drop |
The with_async_drop_2!
Macro
with_async_drop_2!with_async_drop_2!
宏
with_async_drop_2!Automatically calls on scope exit:
async_drop()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/