是否可以在同步函数中编写异步循环?

Is it possible to write an asynchronous loop inside synchronous function?

这是我当前的 Rust 代码

async fn test() {
    ........
    loop {
        ......
        set_timeout(Duration::from_secs(5)).await;
    }
}

我想让我的函数同步,我可以做类似...

fn test() {
    loop {
        async {
            ......
            set_timeout(Duration::from_secs(5)).await;
        }
    }
}

我尝试了如上所示的操作,我从函数中删除了 async 关键字并在循环内创建了一个异步块,但是在进行此更改之后,我的代码不知何故变得无法访问,

我怎样才能使我的“测试”功能保持同步并仍然使我的代码可访问?!

无法访问包含 async 块的代码,因为 async 块不会 执行 内部代码,而是 创建.awaited 的 future 将执行里面的代码。

要在同步函数内执行异步代码,您需要阻塞。这些功能通常由您使用的异步运行时提供。例如,tokio 具有 block_on()(以及许多其他功能)。你这样做:

tokio::runtime::Runtime::new().unwrap().handle().block_on(async {
    // ...
});
// Or by re-using the current runtime, if you have an active one:
tokio::runtime::Handle::current().block_on(async {
    // ...
});

futures crate 提供了一个 runtime-agnostic block_on() 函数,尽管使用它可能性能较低 and/or 会干扰运行时。

请注意,在执行异步代码时进行阻塞(如果外部函数由异步代码调用)是不好的,可能会产生严重的影响。