Best practice: return a blocking future or JoinHandle? #6919
Unanswered
maxcountryman
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi folks,
I have a method,
run
, that's part of the public API of a crate I'm building. The purpose of this method is to start two background tasks: a worker and a scheduler. These tasks need to run in parallel, so they are spawned usingtokio::spawn
and then managed withtokio::select!
. (Note that both tasks run indefinitely, so theselect!
is not expected to resolve under normal operation.)Currently, this run method blocks when called. Callers can
tokio::spawn
the future if they prefer (and generally would, since this crate aims to provide durable background jobs). However, I’m considering an alternative approach: spawning theselect!
future within the run method and returning theJoinHandle
. This would give callers the flexibility to block on the handle or ignore it. That could be something like:Alternatively, I could provide a separate method, maybe called
start
, that wrapsrun
withtokio::spawn
as a convenience.All that said, I'm looking for guidance on common idioms for this pattern and how best to apply them in my specific use case. Which approach is more idiomatic or recommended?
Beta Was this translation helpful? Give feedback.
All reactions