Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 39 ยท Commands and Events

Async Commands and Long-Running Work in Tauri

Keep your Tauri UI responsive: sync versus async commands, async fn with Tokio, spawn_blocking for heavy work, borrowed arguments, progress reporting and cancellation.

A command that takes two seconds is fine if it does not freeze anything, and a disaster if it does. Tauri gives you tools to keep work off the thread that runs your windows. This lesson explains where each kind of command runs and how to pick the right shape for slow work.

Where commands run

  • A synchronous command (fn) runs on the main thread by default, the one that also handles window events. A slow synchronous command can freeze every window.
  • An async command (async fn) runs on Tauri's async runtime (a Tokio thread pool). It does not block the main thread, even if it awaits for a long time.

Tauri's own advice is to make commands that might take a while async.

Rust
use std::time::Duration;

#[tauri::command]
fn slow_sync() -> String {
    std::thread::sleep(Duration::from_secs(3)); // blocks the main thread: UI freezes
    "done".into()
}

#[tauri::command]
async fn slow_async() -> String {
    tokio::time::sleep(Duration::from_secs(3)).await; // yields: UI stays alive
    "done".into()
}

From JavaScript both look identical: await invoke("slow_async"). The difference is entirely in how well the app behaves meanwhile.

You can also keep a sync function but run it off the main thread with the attribute on the thread: spawn a thread yourself, or switch to async.

Async rules in commands

Async commands have restrictions because the future must be able to move between threads:

  1. Borrowed arguments such as &str are not allowed in async fn commands; use owned types: String, Vec<T>.
  2. A command returning Result must have an error type that is serializable (as in Command errors).
  3. When you need State, write State<'_, T> and return a Result, which satisfies the borrow requirements.
Rust
#[tauri::command]
async fn fetch_title(url: String) -> Result<String, String> {   // owned String, not &str
    // use an async HTTP client here
    Ok(format!("title of {url}"))
}

CPU-heavy work: spawn_blocking

async does not make CPU-bound code fast; it only keeps the main thread free. A tight loop inside an async fn still hogs a Tokio worker thread and can starve other async tasks. For heavy computation or blocking APIs (big file hashing, image resizing, a blocking database driver), move it to a dedicated blocking thread:

Rust
#[tauri::command]
async fn hash_file(path: String) -> Result<String, String> {
    tauri::async_runtime::spawn_blocking(move || compute_hash(&path))
        .await
        .map_err(|e| e.to_string())?
}

fn compute_hash(path: &str) -> Result<String, String> {
    // heavy synchronous work here
    Ok(format!("hash-of-{path}"))
}

tauri::async_runtime gives you spawn, spawn_blocking and block_on without choosing a runtime yourself.

Spawning background tasks

Fire-and-forget work that should outlive a command call uses spawn:

Rust
#[tauri::command]
fn start_sync(app: tauri::AppHandle) {
    tauri::async_runtime::spawn(async move {
        // runs after the command returns
        // ... do the sync, then tell the UI:
        use tauri::Emitter;
        let _ = app.emit("sync-finished", true);
    });
}

The command returns immediately; the task reports back through an event, which you meet in Events. For continuous output use a channel.

Progress and cancellation

Two classic needs for long tasks:

  • Progress. Emit events or send channel messages with a percentage as the work proceeds.
  • Cancellation. Keep a flag or a cancellation token in managed state. A second command, cancel_job, sets it; the worker checks it between steps and stops early.
Rust
use std::sync::atomic::{AtomicBool, Ordering};

struct Job { cancelled: AtomicBool }

#[tauri::command]
fn cancel_job(job: tauri::State<'_, Job>) {
    job.cancelled.store(true, Ordering::SeqCst);
}

An AtomicBool needs no mutex, which makes it ideal for simple flags.

Try it: why blocking freezes (stand-in)

JavaScript is single threaded like a UI thread. This stand-in shows a ticking "UI" that keeps updating while a task awaits, and stops while a task blocks.

Node.js Stand-in: async keeps the UI alive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Try it: progress and cancellation (stand-in)

A worker processes items in steps, reports progress, and checks a cancel flag between steps.

Node.js Stand-in: progress reporting with a cancel flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

(The exact step at which the stand-in cancels depends on timer timing, so only the outcome is printed. In a real app you would send each percentage to the UI.)

Try it: spawn_blocking idea in real Rust

Here is runnable Rust (no Tauri) with the same shape: heavy work on a separate thread, result returned through join.

Rust Rust: heavy work on its own thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Choosing the right shape

Work Use
Quick, pure, in-memory plain fn
Network, timers, async file I/O async fn
CPU-heavy or blocking library async fn + spawn_blocking
Output over time async + channel
Notify when finished spawn + event

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does a plain synchronous command run by default?

    Sync commands run on the main thread, so a slow one can freeze windows.
  2. 2. Which argument type is not allowed in an async command?

    Async commands need owned arguments because the future may move between threads.
  3. 3. What is spawn_blocking for?

    It keeps blocking work from starving async worker threads.
  4. 4. Why use an AtomicBool for a cancel flag?

    Atomics are lock-free and ideal for simple flags.

Summary

  • Sync commands run on the main thread; async commands run on the runtime and keep the UI responsive.
  • Async commands need owned arguments and serializable errors.
  • Use spawn_blocking for CPU-heavy or blocking work.
  • Use spawn for background tasks that report back via events or channels.
  • Cancel with a flag in state; report progress with events or channels.

Next: Events