简体   繁体   English

如何使用 Tokio 编写异步方法?

[英]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.

相关问题 如何在 Tokio 运行时上下文中从异步方法调用的非异步方法中等待未来? - How do I await a future inside a non-async method which was called from an async method within the context of a Tokio runtime? 如何在 Tokio 中使用 async/await 语法? - How do I use async/await syntax with Tokio? 如何使用 tokio 0.1 和异步函数递归删除目录? - How do I recursively delete a directory using tokio 0.1 and async functions? 如何在 tokio_postgres 中使用自定义 Tokio 运行时(并且没有 tokio::main 宏)? - How do I use a custom Tokio runtime within tokio_postgres (and without the tokio::main macro)? 如何在Tokio中安排重复任务? - How do I schedule a repeating task in Tokio? 您如何在tokio :: run futures内编写测试断言? - How do you write test assertions inside of tokio::run futures? 异步 tokio 应用程序中的读/写问题(初学者) - Read/write problem in async tokio application (beginner) 调用 tokio::spawn 时如何解决“特征绑定 `[closure]: tokio::prelude::Future` 不满足”? - How do I solve “the trait bound `[closure]: tokio::prelude::Future` is not satisfied” when calling tokio::spawn? 如何将Tokio线程池限制为一定数量的本机线程? - How do I limit the Tokio threadpool to a certain number of native threads? 如何在#[no_std]环境中使用Tokio Reactor? - How do I use Tokio Reactor in a #[no_std] environment?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM