FAQ - Help and questions

How do I show progress from a worker thread in a GUI app?

#threads#channels#progress#guipublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Define an enum of messages such as Progress(percent) and Done(result), send them from the worker through a channel, and read them in the UI's update step, where each message changes the state the window shows. The worker never touches the UI. A std-only program with the pattern was compiled and run.

Checked with rustc 1.93.0, Windows 11; compiled and run (std only, no GUI).

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

#1

Answer#

Use one channel that carries a small enum. Everything the UI needs to know, progress and the final result or error, is a variant. The worker sends; the UI reads in its normal update step and stores the values in its state; the next frame draws the state.

src/main.rsrust
use std::sync::mpsc;
use std::thread;

enum Msg {
    Progress(u32), // percent
    Done(Result<usize, String>),
}

fn main() {
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        let items = 8;
        for i in 1..=items {
            // ... real work for one item here ...
            let _ = tx.send(Msg::Progress(i * 100 / items));
        }
        let _ = tx.send(Msg::Done(Ok(items as usize)));
    });

    // In a real app this match sits in the per-frame or per-event update function.
    for msg in rx {
        match msg {
            Msg::Progress(p) => println!("progress {p}%"),
            Msg::Done(Ok(n)) => println!("done, {n} items"),
            Msg::Done(Err(e)) => println!("failed: {e}"),
        }
    }
}
text
progress 12%
progress 25%
progress 37%
progress 50%
progress 62%
progress 75%
progress 87%
progress 100%
done, 8 items

Integer division makes the percentages round down (12, 25, 37 ...). In the real app, replace the println! calls with assignments such as self.percent = p; and draw a progress bar from self.percent.

Keep messages small and send them only when something changed visibly. A message per byte of a large file floods the channel; one per percent point or per 50 ms does not.

Common mistakes#

  • Sending progress through a shared Mutex<f32> that the UI polls without telling the toolkit to redraw. The channel plus a repaint request (egui) or a message (iced) is clearer.
  • Ending the work without a Done message. The UI then cannot tell "finished" from "stuck".
  • Reporting errors only with println! in the worker. Send them as a message so the window can show them.

Can the worker send results to several windows?#

One channel has one receiver. For several receivers, create one channel for each.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet