4 个版本
0.2.0 | 2020 年 6 月 24 日 |
---|---|
0.1.2 | 2020 年 6 月 5 日 |
0.1.1 | 2020 年 4 月 22 日 |
0.1.0 | 2020 年 4 月 21 日 |
#1937 在 异步
11KB
144 行
tokio_safe_block_on
提供从同步上下文执行异步代码的能力,而不会阻塞 tokio 核心线程或使 CPU 忙碌循环。
示例
#[tokio::main(threaded_scheduler)]
async fn main() {
// we need to ensure we are in the context of a tokio task
tokio::task::spawn(async move {
// some library api may take a sync callback
// but we want to be able to execute async code
(|| {
let r = tokio_safe_block_on::tokio_safe_block_on(
// async code to poll synchronously
async move {
// simulate some async work
tokio::time::delay_for(
std::time::Duration::from_millis(2)
).await;
// return our result
"test"
},
// timeout to allow async execution
std::time::Duration::from_millis(10),
).unwrap();
// note we get the result inline with no `await`
assert_eq!("test", r);
})()
})
.await
.unwrap();
}
依赖
~4MB
~65K SLoC