Skip to main content

spawn_blocking

Function spawn_blocking 

Source
pub fn spawn_blocking<T, F>(
    f: F,
) -> impl Future<Output = Result<T, BlockingError>>
where F: FnOnce() -> T + Send + 'static, T: Send + 'static,
Expand description

Run f on a dedicated OS thread and resolve to its return value. Await the returned future inside a spawn_local body to keep heavy/blocking work off the UI thread:

ctx.spawn_local(async move {
    match teksilo_async::spawn_blocking(move || std::fs::read(path)).await {
        Ok(bytes) => loaded.set(bytes.ok()),         // back on the UI thread
        Err(e) => status.set(format!("load failed: {e}")),
    }
})
.detach();

Needs no async runtime: the worker is a plain std::thread, and the result crosses back through a one-shot channel whose waker nudges the executor. This is the runtime-free path; teksilo-tokio / teksilo-async-std add the ability to .await native-ecosystem futures (timers, sockets) directly.

A panic in f is caught on the worker thread and surfaced as BlockingError::Panicked — it does not unwind through the UI thread.