async
/await
从高层次上看,异步 Rust 代码与“正常”的顺序代码非常类似:
Speaker Notes
关键点:
-
请注意,这只是一个简单的示例,用于展示语法。其中没有长时间运行的操作或任何真正的并发!
-
异步调用的返回类型是什么?
- 在
main
中使用let future: () = async_main(10);
来查看类型。
- 在
-
The “async” keyword is syntactic sugar. The compiler replaces the return type with a future.
-
你不能将
main
声明为异步函数,除非在编译器中加入额外的指令来告诉它如何使用返回的 future。 -
You need an executor to run async code.
block_on
blocks the current thread until the provided future has run to completion. -
.await
会异步地等待另一个操作的完成。与block_on
不同,.await
不会阻塞当前线程。 -
.await
can only be used inside anasync
function (or block; these are introduced later).