FAQ - Help and questions

How do I let the user cancel a long background task in a desktop app?

#threads#cancel#atomics#guipublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Share an AtomicBool between the UI and the worker. The Cancel button sets it, and the worker checks it between small units of work and returns early. A thread cannot be killed safely from outside, so the worker has to cooperate. A std-only example 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#

Rust has no safe way to stop another thread from outside. The worker must stop itself, and the usual way is a shared flag: an AtomicBool inside an Arc. The UI sets it; the worker reads it often enough that it reacts quickly and leaves its work in a clean state.

src/main.rsrust
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;

fn main() {
    let cancel = Arc::new(AtomicBool::new(false));
    let flag = Arc::clone(&cancel);
    let worker = thread::spawn(move || {
        let mut done = 0u32;
        while done < 1000 {
            if flag.load(Ordering::Relaxed) {
                return (done, true); // stop at a safe point and report it was cancelled
            }
            thread::sleep(Duration::from_millis(5)); // one unit of work
            done += 1;
        }
        (done, false)
    });

    thread::sleep(Duration::from_millis(50));
    cancel.store(true, Ordering::Relaxed); // the Cancel button
    let (done, cancelled) = worker.join().unwrap();
    println!("cancelled = {cancelled}, stopped before the end = {}", done < 1000);
}
text
cancelled = true, stopped before the end = true

For a flag like this, Ordering::Relaxed is enough: only the flag itself is shared, and nothing else relies on it being seen in a particular order with other memory.

Design points:

  • Check between units of work. The check cannot interrupt a single long call (a large copy, a blocking read). Split work into chunks small enough that cancel feels immediate.
  • Report the outcome. Send a Cancelled message, not silence, so the UI can leave its "working" state.
  • Clean up. If the worker was writing a file, delete the partial file or write to a temporary name first (see the thread on saving files safely).

Common mistakes#

  • Setting the flag and then calling join() on the UI thread. If the worker is slow to notice, the window freezes. Wait for the Cancelled message instead.
  • Reusing one flag for the next task without resetting it. Create a new flag for each task.

What about async tasks?#

They are cancelled by dropping them (or through the runtime's own cancellation tools), which is a different mechanism; read your runtime's documentation.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet