首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >是否有类似于recv_timeout函数的异步rust特性?

是否有类似于recv_timeout函数的异步rust特性?
EN

Stack Overflow用户
提问于 2021-07-07 03:56:29
回答 1查看 99关注 0票数 0

我试图在非异步上下文中调用一个异步函数,但我真的很难使用它。

对我来说,通道使用起来要容易得多--它非常简单直观。

recv的意思是阻塞线程,直到你收到一些东西。

try_recv的意思是看看是否有东西在那里,否则就会出错。

recv_timeout意味着尝试一定的毫秒数,如果在超时后没有任何内容,则会出错。

我在std::future::Future的文档中到处寻找,但我没有看到任何类似的方法。我尝试过的函数都不是简单的解决方案,它们要么接受,要么给出奇怪的结果,需要更多的解包。

EN

回答 1

Stack Overflow用户

发布于 2021-07-08 01:28:14

标准库中的Future特征非常初级,并为其他库的构建提供了稳定的基础。

异步运行时(如tokio、async-std、smol)包括一些组合符,它们可以把未来变成另一个未来。tokio库有一个名为timeout的这样的组合子。

以下是一个示例(playground link),当尝试在oneshot频道上接收时,它会在1秒后超时。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68279793

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文