我试图在非异步上下文中调用一个异步函数,但我真的很难使用它。
对我来说,通道使用起来要容易得多--它非常简单直观。
recv的意思是阻塞线程,直到你收到一些东西。
try_recv的意思是看看是否有东西在那里,否则就会出错。
recv_timeout意味着尝试一定的毫秒数,如果在超时后没有任何内容,则会出错。
我在std::future::Future的文档中到处寻找,但我没有看到任何类似的方法。我尝试过的函数都不是简单的解决方案,它们要么接受,要么给出奇怪的结果,需要更多的解包。
发布于 2021-07-08 01:28:14
标准库中的Future特征非常初级,并为其他库的构建提供了稳定的基础。
异步运行时(如tokio、async-std、smol)包括一些组合符,它们可以把未来变成另一个未来。tokio
库有一个名为timeout
的这样的组合子。
以下是一个示例(playground link),当尝试在oneshot频道上接收时,它会在1秒后超时。
use std::time::Duration;
use tokio::{runtime::Runtime, sync::oneshot, time::{timeout, error::Elapsed}};
fn main() {
// Create a oneshot channel, which also implements `Future`, we can use it as an example.
let (_tx, rx) = oneshot::channel::<()>();
// Create a new tokio runtime, if you already have an async environment,
// you probably want to use tokio::spawn instead in order to re-use the existing runtime.
let rt = Runtime::new().unwrap();
// block_on is a function on the runtime which makes the current thread poll the future
// until it has completed. async move { } creates an async block, which implements `Future`
let output: Result<_, Elapsed> = rt.block_on(async move {
// The timeout function returns another future, which outputs a `Result<T, Elapsed>`. If the
// future times out, the `Elapsed` error is returned.
timeout(Duration::from_secs(1), rx).await
});
println!("{:?}", output);
}
https://stackoverflow.com/questions/68279793
复制相似问题