3

我想轮询一个异步函数:

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

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

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",
]
4

1 回答 1

6

要使用 Tokio 对未来进行轮询,您需要一个Runtime.

这仅在 crate 功能上受支持rt

[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宏:

这仅在 crate 功能上受rt支持macros

[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(())
}

如果您想要您指定的确切语法(这不是“启用 Tokio 轮询未来的最小功能集”),那么运行时错误会指导您:

默认运行时风格是multi_thread,但该rt-multi-thread功能已禁用。

[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(())
}

也可以看看:

于 2021-04-05T23:36:04.220 回答