expression

Detect a runtime context

Detect whether the caller is in a Tokio runtime context without relying on a panic. Entering a context is not itself driving scheduled tasks. Tokio is an external dependency; see the proposed Cargo manifest. Expected stdout (not executed): true true Common mistake: Treating current runtime detection as proof that a particular driver is enabled.

Formal Syntax & Structure

rust syntaxrust
tokio::runtime::Handle::try_current()

Working Example

Example Snippetrust
fn main() {    println!("{}", tokio::runtime::Handle::try_current().is_err());    let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();    rt.block_on(async {        println!("{}", tokio::runtime::Handle::try_current().is_ok());    });}
Rust Reference