如何在具有内部循环的不同任务中使用 Tokio oneshot 发送器和接收器?

How do I use a Tokio oneshot sender and receiver on different tasks with inner loops?

不知道如何处理这里的借用检查器。

use tokio::sync::oneshot; // 1.0.2

fn main() {
    let (sender, receiver) = oneshot::channel::<u8>();
    tokio::spawn(async move {
        loop {
            sender.send(3).unwrap();
        }
    });
}

创建此错误:

error[E0382]: use of moved value: `sender`
 --> src/main.rs:7:13
  |
7 |             sender.send(3).unwrap();
  |             ^^^^^^ value moved here, in previous iteration of loop
  |
  = note: move occurs because `sender` has type `tokio::sync::oneshot::Sender<u8>`, which does not implement the `Copy` trait

你不知道。这就是 oneshot 通道的全部要点:它最多只能使用一次:

A channel for sending a single message between asynchronous tasks.

tokio::sync::oneshot

听起来您想要其他类型的频道,例如 tokio::sync::mpsc


what if I only want to send one message at the start of the loop?

然后执行循环开始前的代码:

use tokio::sync::oneshot; // 1.0.2

fn main() {
    let (sender, receiver) = oneshot::channel::<u8>();
    tokio::spawn(async move {
        sender.send(3).unwrap();
        
        loop {
            // Do things
        }
    });
}

如果您不得不将它放在循环中,您需要动态地将值标记为不再存在并处理这种情况。在这里,我使用 Optionif let:

use tokio::sync::oneshot; // 1.0.2

fn main() {
    let (sender, receiver) = oneshot::channel::<u8>();
    tokio::spawn(async move {
        let mut sender = Some(sender);
        
        loop {
            if let Some(sender) = sender.take() {
                sender.send(3).unwrap();
            }
            // Do things
        }
    });
}