From dd0ce06828f3630a26b018d7470891c19353d0a7 Mon Sep 17 00:00:00 2001 From: Mike Dilger Date: Sun, 1 Jan 2023 11:54:13 +1300 Subject: [PATCH] Start tokio runtime on main thread and enter context there, so non-async code can spawn tasks too --- src/main.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index 9bdf6198..a9c5f967 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,11 +46,16 @@ fn main() -> Result<(), Error> { let settings = crate::settings::Settings::blocking_load()?; *GLOBALS.settings.blocking_write() = settings; - // Start async code - // We do this on a separate thread because egui is most portable by - // being on the main thread. - let async_thread = thread::spawn(|| { - let rt = tokio::runtime::Runtime::new().unwrap(); + // We create and enter the runtime on the main thread so that + // non-async code can have a runtime context within which to spawn + // async tasks. + let rt = tokio::runtime::Runtime::new().unwrap(); + let _main_rt = rt.enter(); // <-- this allows it. + + // We run our main async code on a separate thread, not just a + // separate task. This leave the main thread for UI work only. + // egui is most portable when it is on the main thread. + let async_thread = thread::spawn(move || { rt.block_on(tokio_main()); });