How does tokio::runtime::Handle.block_on
differ to tokio::runtime::Runtime.block_on
? The Handle.block_on
causes some code to hang whereas the Runtime.block_on
works fine.
This is how I create the Handle
. The Runtime
is the same minus the last 2 lines.
let runtime = runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.handle() // not needed for Runtime
.clone(); // ---
Then I call a function which with this:
async fn run(){
// calls get data
}
self.runtime.block_on(run())
This is the code where it hangs. When running from the Runtime
it works fine, with the Handle
it hangs at TcpStream::connect()
.
async fn get_data(addr: String) -> Result<Data> {
let c = TcpStream::connect(addr.clone()).await?; // hangs here
let t = get_data_from_connect(c).await?;
return Ok(t);
}
I fixed this by making sure that the Runtime
object does not go out of scope and get dropped. I was under the impression that only the Handle
is needed to keep the runtime alive but only the Runtime
object itself can.