本文介绍了可以使用Tokio轮询未来的最小功能集是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想轮询一个异步函数:

I want to poll an async function:

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    some_function().await;
}

我当前正在激活所有功能:

I am currently activating all features:

tokio = { version = "1.4.0", features = ["full"] }

其中哪些是必要的?

full = [
  "fs",
  "io-util",
  "io-std",
  "macros",
  "net",
  "parking_lot",
  "process",
  "rt",
  "rt-multi-thread",
  "signal",
  "sync",
  "time",
]

推荐答案

要启用对Tokio的未来轮询,您需要 运行时 .

To enable polling a future with Tokio, you need a Runtime.

[dependencies]
tokio = { version = "1.4.0", features = ["rt"] }
fn main() -> Result<(), Box<dyn std::error::Error>> {
    tokio::runtime::Builder::new_current_thread()
        .build()
        .unwrap()
        .block_on(some_function())
}

async fn some_function() -> Result<(), Box<dyn std::error::Error>> {
    Ok(())
}

如果要使用 tokio :: main 宏:

If you want to use the tokio::main macro:

[dependencies]
tokio = { version = "1.4.0", features = ["rt", "macros"] }
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    some_function().await
}

async fn some_function() -> Result<(), Box<dyn std::error::Error>> {
    Ok(())
}

如果您想要指定的 exact 语法(这不是启用Tokio轮询未来的最小功能集"),则运行时错误将指导您:

If you want the exact syntax you've specified (which is not the "smallest feature set to enable polling a future with Tokio"), then the runtime error guides you:

[dependencies]
tokio = { version = "1.4.0", features = ["rt", "rt-multi-thread", "macros"] }
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    some_function().await
}

async fn some_function() -> Result<(), Box<dyn std::error::Error>> {
    Ok(())
}

另请参阅:

这篇关于可以使用Tokio轮询未来的最小功能集是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 01:06