小编Joh*_*ell的帖子

如何在另一个任务中生成长时间运行的 Tokio 任务而不阻塞父任务?

我正在尝试构建一个对象,该对象可以管理来自 websocket 的提要,但能够在多个提要之间切换。

有一个Feed特点:

trait Feed {
    async fn start(&mut self);
    async fn stop(&mut self);
}
Run Code Online (Sandbox Code Playgroud)

共有三个结构体实现FeedABC

start被调用时,它会启动一个无限循环,监听来自 websocket 的消息并处理每条传入的消息。

我想实现一个FeedManager维护单个活动源但可以接收命令来切换它正在使用的源的命令。

enum FeedCommand {
    Start(String),
    Stop,
}

struct FeedManager {
    active_feed_handle: tokio::task::JoinHandle,
    controller: mpsc::Receiver<FeedCommand>,
}

impl FeedManager {
    async fn start(&self) {
        while let Some(command) = self.controller.recv().await {
            match command {
                FeedCommand::Start(feed_type) => {
                    // somehow tell the active feed to stop (need channel probably) or …
Run Code Online (Sandbox Code Playgroud)

rust rust-tokio

5
推荐指数
2
解决办法
6553
查看次数

标签 统计

rust ×1

rust-tokio ×1