Answer#
The UI thread must return to its event loop quickly (see the thread on the event loop). So slow work goes on a second thread, and the two threads talk through a channel:
- The UI creates a channel and moves the sender into the new thread.
- The thread does the slow work and sends the result.
- The UI asks the receiver "is there anything yet?" with
try_recv, which never waits, once per frame or per event.
use std::sync::mpsc;
use std::thread;
fn slow_sum(n: u64) -> u64 {
(1..=n).fold(0u64, |a, b| a.wrapping_add(b * b))
}
fn main() {
let (tx, rx) = mpsc::channel::<u64>();
// "Button pressed": start the work on its own thread and return at once.
let worker = thread::spawn(move || {
let result = slow_sum(50_000_000);
let _ = tx.send(result); // ignore the error if the window (receiver) is already gone
});
// The UI loop keeps running; each frame it asks "is there a result yet?" without waiting.
let mut frames = 0u32;
let result = loop {
match rx.try_recv() {
Ok(v) => break v,
Err(mpsc::TryRecvError::Empty) => frames += 1, // draw a frame, stay responsive
Err(mpsc::TryRecvError::Disconnected) => panic!("worker died"),
}
thread::sleep(std::time::Duration::from_millis(1));
};
worker.join().unwrap();
println!("result = {result}, UI kept running: {}", frames > 0);
}result = 13919798230507451072, UI kept running: true(The sum uses wrapping arithmetic so it cannot overflow-panic; the number itself is not important.)
In a real program the loop is the toolkit's frame or event handler, and thread::sleep is not needed: the toolkit calls you again by itself. What each toolkit needs to wake up when the result arrives is covered in the egui thread.
Common mistakes#
- Calling
worker.join()in the UI thread to "wait for the result". It blocks exactly like the slow work did. - Sending UI objects (widgets, window handles) to the worker. Send plain data and let the UI thread update the widgets; see the thread on
Send. - Unwrapping
tx.send(..)in the worker. If the user closes the window, the receiver is gone andsendreturns an error; ignoring it lets the thread finish quietly.
Related questions#
Should I use async instead of threads?#
Async is a good fit for many waiting operations (network, timers). For heavy computation a thread is simpler, because async tasks that compute without waiting block their executor thread. Either way the UI receives the result as a message.
How many threads can I start?#
One per task is fine for a few tasks. For many small tasks, use a thread pool crate instead of one thread each.
Sources#
- std::sync::mpsc::Receiver::try_recv: https://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html#method.try_recv (read 2026-12-05)
- The Rust Book, "Using Message Passing to Transfer Data Between Threads": https://doc.rust-lang.org/book/ch16-02-message-passing.html (read 2026-12-05)