tokio icon indicating copy to clipboard operation
tokio copied to clipboard

Consider implementing JoinHandle::try_join

Open andreastedile opened this issue 10 months ago • 4 comments

Consider the following code using a JoinHandle:

if handle.is_finished() {
    let result = handle.await;
    match result {
        Ok(result) => {}
        Err(error) => {}
    }
}

I think that it would a bit more ergonomic to be able to just do:

match handle.try_join() {
    Some(Ok(result)) => {} // Task has completed successfully
    Some(Err(error)) => {} // Task has completed with error
    None => {} // Task has not completed yet
}

As pointed out on Discord, there is the issue that that handle.await will panic if called after handle.try_join returns not None.

andreastedile avatar Apr 15 '24 16:04 andreastedile

there is the issue that that handle.await will panic if called after handle.try_join returns not None

Though you should call handle.try_join().await. Why would you call handle.await after try_join?

dd-dreams avatar Apr 25 '24 12:04 dd-dreams

This is presented here in an async context. I found this while looking for the ideal way to poll a JoinHandle from sync code. IMO this would be convenient for that case. Similar to some of the use cases for https://docs.rs/tokio/1.39.2/tokio/sync/oneshot/struct.Receiver.html#method.try_recv.

Imberflur avatar Aug 06 '24 22:08 Imberflur

I suppose this could make sense to have, though the footgun about .await is unfortunate.

Darksonn avatar Aug 07 '24 08:08 Darksonn

the footgun about .await is unfortunate

Yeah... FWIW I don't have a case where this is essential, it would just be more convenient. So I could see it not being worth the additional footgun. At least for my particular case.

I.e. I could either pass results through a oneshot channel, check is_finished and hope that ensures FutureExt::now_or_never succeeds, or just manually poll the future with a dummy waker.

Imberflur avatar Aug 07 '24 14:08 Imberflur