#future #tokio #task #prevent #shield #wrapping #aborted

tokio-shield

通过将它们封装在任务中以防止futures被终止

2次发布

0.1.1 2023年9月20日
0.1.0 2023年5月25日

#1512 in 异步

Download history 17/week @ 2024-04-14 9/week @ 2024-04-21 15/week @ 2024-04-28 17/week @ 2024-05-05 18/week @ 2024-05-12 17/week @ 2024-05-19 15/week @ 2024-05-26 9/week @ 2024-06-02 11/week @ 2024-06-09 14/week @ 2024-06-16 13/week @ 2024-06-23 30/week @ 2024-06-30 11/week @ 2024-07-07 17/week @ 2024-07-14 18/week @ 2024-07-21 37/week @ 2024-07-28

100 每月下载量
用于 poem-ext

MIT 许可证

7KB
71

check test codecov Version dependency status

tokio-shield

通过将它们封装在任务中以防止Rust中的futures被终止。

示例

use std::time::Duration;
use tokio::{sync::oneshot, time::sleep};
use tokio_shield::Shield;

#[tokio::main]
async fn main() {
    let (tx, mut rx) = oneshot::channel();

    // Create and shield a future that waits for 10ms and then returns a value
    // via a oneshot channel.
    let future = async {
        sleep(Duration::from_millis(10)).await;
        tx.send(42).unwrap();
    }.shield();

    // Spawn a task to run this future, but cancel it after 5ms.
    let task = tokio::spawn(future);
    sleep(Duration::from_millis(5)).await;
    task.abort();
    sleep(Duration::from_millis(5)).await;

    // After 10ms the value can successfully be read from the oneshot channel,
    // because `shield` prevented our future from being canceled.
    assert_eq!(rx.try_recv().unwrap(), 42);
}

依赖项

~2.6–4MB
~61K SLoC