[英]How do I write an async method with Tokio?
I'm trying to write a library that will connect to remote servers and exchange data.我正在尝试编写一个可以连接到远程服务器并交换数据的库。 I did this in C++ using Boost::Asio and am trying to do the same with Rust.
我在 C++ 中使用 Boost::Asio 执行此操作,并尝试对 Rust 执行相同操作。
One of the problems I have is mapping concepts from Asio, like async_write/read to Tokio, starting with the fact that seemingly all Tokio examples demand that I replace my main()
with an async main()
, while I would like to encapsulate all my async code in structures and associated implementations.我遇到的问题之一是从 Asio 映射概念,例如 async_write/read 到 Tokio,首先是似乎所有 Tokio 示例都要求我用
async main()
替换我的main()
() ,而我想封装所有我在结构和相关实现中的异步代码。
Is it possible to use Tokio without replacing main()
?是否可以在不替换
main()
的情况下使用 Tokio ? Is mio
perhaps the only way? mio
可能是唯一的方法吗?
You can create a runtime manually using Runtime::new() which is what the tokio main macro is doing under the hood.您可以使用Runtime::new()手动创建运行时,这是 tokio 主宏在后台执行的操作。 It's just for an awful lot of apps, especially examples that's just boilerplate.
它仅适用于大量应用程序,尤其是样板示例。 So the macro automates the simple case.
所以宏自动化了简单的情况。
However, depending on the context of your library, it may be more idiomatic to provide a future based API, and then leave the app consumer to set up the runtime.但是,根据您的库的上下文,提供基于未来的 API 可能更惯用,然后让应用程序使用者设置运行时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.