FAQ - Help and questions

Why does my egui window not update when a background thread finishes?

#egui#threads#eframe#repaintpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

egui redraws only when it receives input or is asked to, so a result sent from a worker thread can sit in the channel until the mouse moves. Clone the egui Context into the thread and call request_repaint after each send. The code passed cargo check.

Checked with rustc 1.93.0, Windows 11, eframe 0.35.0; `cargo check` only, the window was not opened. The behaviour description is from egui's documentation for request_repaint.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

egui does not redraw continuously by default. It draws a frame when something happens (input, a timer, an animation) and sleeps otherwise, which saves power. A worker thread that sends a message into a channel does not count as "something happens", so the UI may not run ui and may not read the channel until the user moves the mouse.

The fix is to wake the UI from the thread: egui::Context is cheap to clone and safe to use from other threads, and request_repaint() tells egui to run another frame.

src/main.rsrust
use eframe::egui;
use std::sync::mpsc;
use std::time::Duration;

struct App {
    rx: mpsc::Receiver<String>,
    lines: Vec<String>,
}

impl App {
    fn new(ctx: egui::Context) -> Self {
        let (tx, rx) = mpsc::channel();
        std::thread::spawn(move || {
            for i in 1..=5 {
                std::thread::sleep(Duration::from_secs(1)); // slow work
                if tx.send(format!("finished step {i}")).is_err() {
                    return; // the window was closed
                }
                ctx.request_repaint(); // wake the UI: it may be asleep waiting for input
            }
        });
        App { rx, lines: Vec::new() }
    }
}

impl eframe::App for App {
    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        while let Ok(line) = self.rx.try_recv() {
            self.lines.push(line);
        }
        egui::CentralPanel::default().show(ui, |ui| {
            for l in &self.lines {
                ui.label(l);
            }
        });
    }
}

fn main() -> eframe::Result {
    eframe::run_native(
        "Background work",
        eframe::NativeOptions::default(),
        Box::new(|cc| Ok(Box::new(App::new(cc.egui_ctx.clone())))),
    )
}

This compiled with cargo check using eframe 0.35.0 on Windows 11. The window was not run.

Two details: the context is taken from cc.egui_ctx in the creation closure, because that is where the app is built; and try_recv is in a while let so all waiting messages are read in one frame.

Common mistakes#

  • Calling ctx.request_repaint() inside ui on every frame to "keep it fresh". That redraws forever and uses CPU. Request a repaint only when something changed, or use request_repaint_after(duration) for a periodic update such as a clock.
  • Using a blocking recv() inside ui. It waits for the worker and freezes the window.

Is the Context safe to share?#

egui documents Context as cheap to clone (it is a handle) and usable from several threads; read the type's documentation for details such as locking.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet