tokio::spawn(my_future).await 和 my_future.await 有什么区别?

hbo*_*cio 12 rust rust-tokio

给定一个异步函数及其相应的未来,让我们说:

async fn foo() -> Result<i32, &'static str> {
    // ...
}

let my_future = foo();
Run Code Online (Sandbox Code Playgroud)

除了使用 tokio::spawn().await 之外,只使用 .await 等待它有什么区别?

// like this...
let result1 = my_future.await;

// ... and like this
let result2 = tokio::spawn(my_future).await;
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 14

通常不会等待生成的任务(或至少不会立即等待)。更常见的是简单地写:

tokio::spawn(my_future);
Run Code Online (Sandbox Code Playgroud)

省略.await,任务将在后台运行,而当前任务继续。立即调用.await阻塞当前任务。spawn(task).await实际上与task.await. 这类似于创建一个线程并立即加入它,这同样毫无意义。

生成的任务不需要像裸期货那样等待。等待他们是可选的。那么什么时候可以等待呢?如果阻止当前任务,直到生成的任务完成。

let task = tokio::spawn(my_future);

// Do something else.
do_other_work();

// Now wait for the task to complete, if it hasn't already.
task.await;
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要结果,但需要在开始任务和收集结果之间做一些工作。

let task = tokio::spawn(my_future);

// Do something else.
do_other_work();

// Get the result.
let result = task.await;
Run Code Online (Sandbox Code Playgroud)

  • @hbobenicio 我今天也有同样的问题。看起来像 `tokio::spawn` 和 `thread::spawn` 一样,当你生成时,它会在后台运行。 (2认同)