【发布时间】:2021-08-19 00:14:50
【问题描述】:
根据当前运行环境获取 tokio 运行时句柄的惯用方式是什么?
- 对于已经在 tokio 运行时运行的方法,我想使用
Handle.try_current().unwrap()来获取当前的。 - 对于未在 tokio 中运行的方法,我可以创建一个新方法:
Runtime::new().unwrap().handle()。
但是,当我将代码编写为:
fn get_runtime_handle() -> Handle {
match Handle::try_current() {
Ok(h) => h,
Err(_) => Runtime::new().unwrap().handle().clone(),
}
}
async fn a_async() -> Result<()> {
....
}
fn a() -> Result<()> {
let handle = get_runtime_handle();
handle.block_one (async { a_async().await; })
}
fn main() -> Result<()> {
a();
Ok(())
}
并在里面调用tokio::fs::read_dir,代码崩溃Error: Custom { kind: Other, error: "background task failed" }。
当我在 main 中将 handle.block_on 替换为 Runtime::new().unwrap().handle().block_on 时,代码运行成功。
我想我的get_runtime_handle 函数有问题,正确的表达方式是什么?
完整的可运行代码是here。
此外,当 get_runtime_handle 方法在 tokio 运行时内运行时,项目中的其他单元测试会抱怨:
thread 'main' panicked at 'Cannot start a runtime from within a runtime.
This happens because a function (like `block_on`) attempted to block the
current thread while the thread is being used to drive asynchronous tasks.
【问题讨论】:
标签: rust rust-tokio