Answer#
Every GUI program, whatever the toolkit, has one loop at its core:
- Wait until something happens.
- Handle that one event.
- Go back to 1.
The things that happen are events: a mouse click, a key press, a window resize, "the window needs redrawing", a timer, a request to close. The operating system delivers them to your program; the toolkit turns them into calls to your code (a callback, a match on an enum, or the ui method of egui).
The rule that follows is simple: your handler runs on the same thread as the loop. While it runs, the loop cannot take the next event, so the window cannot redraw, resize smoothly or close. If a handler takes two seconds, the window is frozen for two seconds, and the system may mark the window as "not responding".
The small program below has no window, but its structure is the same: events arrive on a channel, the loop handles them one by one and quickly.
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
enum Event {
Click,
Tick,
Quit,
}
fn main() {
let (tx, rx) = mpsc::channel();
// Something outside the loop produces events (here: threads standing in for the OS).
let t = tx.clone();
thread::spawn(move || {
for _ in 0..3 {
thread::sleep(Duration::from_millis(20));
t.send(Event::Tick).unwrap();
}
t.send(Event::Click).unwrap();
t.send(Event::Quit).unwrap();
});
drop(tx);
// The event loop: wait for an event, handle it quickly, go back to waiting.
let mut ticks = 0;
for event in rx {
match event {
Event::Tick => ticks += 1,
Event::Click => println!("click handled after {ticks} ticks"),
Event::Quit => break,
}
}
println!("loop ended");
}click handled after 3 ticks
loop endedReal toolkits add one thing: the part that waits is provided by the operating system, so the loop uses no CPU while nothing happens. See the thread on a background thread for the fix to slow handlers.
Common mistakes#
- Calling
thread::sleep, a blocking network call, a big file read or a long computation in a click handler. - Starting a second event loop inside a handler (for example by running a nested dialog loop) without knowing what the toolkit does with it.
- Spinning in a
loop {}that polls for something. Wait on a channel, or let the toolkit wake you.
Related questions#
Does every toolkit have the loop in my code?#
No. In egui and iced you call run_native or iced::run and the library owns the loop; it calls your code. With winit you write the handler that the loop calls; see the winit thread.
Is a callback always on the loop's thread?#
For the toolkits in this category, the code you give to the toolkit (ui, update, view, callbacks) is called on the thread that runs the loop. Check the toolkit's documentation for any exception before using other threads.
Sources#
- winit documentation, event loop and ApplicationHandler: https://docs.rs/winit/0.30.13/winit/ (read 2026-12-05)
- std::sync::mpsc: https://doc.rust-lang.org/std/sync/mpsc/ (read 2026-12-05)