Async-std JoinHandle.cancel() take ownership of self work around?

I am trying to port the crate tokio_kcp to use async_std .

The listener has a struct:

pub struct KcpListener {
    udp: Arc<UdpSocket>,
    accept_rx: mpsc::Receiver<(KcpStream, SocketAddr)>,
    task_watcher: JoinHandle<()>,
}

and the method drop

impl Drop for KcpListener {
    fn drop(&mut self) {
        self.task_watcher.abort();
    }
}

so when the listener is dropped, it also abort the JoinHandle.

However, porting this to async_std raised a problem: async_std::task::JoinHandle does have an equivalent cancel() function to cancel the task, but it takes the ownership of self.

  --> src\listener.rs:42:9
   |
42 |         self.task_watcher.cancel();
   |         ^^^^^^^^^^^^^^^^^ -------- `self.task_watcher` moved due to this method call
   |         |
   |         move occurs because `self.task_watcher` has type `async_std::task::JoinHandle<()>`, which does not implement the `Copy` trait

And apparently not cancelling the handler before dropping would cause the task to dangle forever, i.e. overflowing the stack.

So is there any work around to this?

Thank you.

1 Like

Put it in an Option and then .take().

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.