16 个版本 (6 个重大更新)
0.7.0 | 2022 年 1 月 19 日 |
---|---|
0.6.1 | 2021 年 10 月 28 日 |
0.5.1 | 2021 年 10 月 15 日 |
0.4.1 | 2021 年 10 月 15 日 |
0.1.2 | 2019 年 11 月 12 日 |
#295 在 异步
57,064 每月下载量
在 57 个 Crates 中使用 (6 个直接使用)
24KB
386 行
stop-token
异步 Rust 的协作取消
请参阅 crate 文档以获取详细信息
您可以使用此 crate 创建通过 StopToken
接收的截止日期
use async_std::prelude::*;
use async_std::{stream, task};
use stop_token::prelude::*;
use stop_token::StopSource;
use std::time::Duration;
#[async_std::main]
async fn main() {
// Create a stop source and generate a token.
let src = StopSource::new();
let deadline = src.token();
// When stop source is dropped, the loop will stop.
// Move the source to a task, and drop it after 100 millis.
task::spawn(async move {
task::sleep(Duration::from_millis(100)).await;
drop(src);
});
// Create a stream that generates numbers until
// it receives a signal it needs to stop.
let mut work = stream::repeat(12u8).timeout_at(deadline);
// Loop over each item in the stream.
while let Some(Ok(ev)) = work.next().await {
println!("{}", ev);
}
}
或 Instant
创建基于时间的截止日期
use async_std::prelude::*;
use async_std::stream;
use stop_token::prelude::*;
use std::time::{Instant, Duration};
#[async_std::main]
async fn main() {
// Create a stream that generates numbers for 100 millis.
let deadline = Instant::now() + Duration::from_millis(100);
let mut work = stream::repeat(12u8).timeout_at(deadline);
// Loop over each item in the stream.
while let Some(Ok(ev)) = work.next().await {
println!("{}", ev);
}
}
依赖关系
~0.4–11MB
~108K SLoC