tokio_safe_block_on

Crates.iotokio_safe_block_on
lib.rstokio_safe_block_on
version0.2.0
sourcesrc
created_at2020-04-21 18:30:59.674729
updated_at2020-06-24 18:47:00.596706
descriptionProvides the ability to execute async code from a sync context, without blocking a tokio core thread or busy looping the cpu.
homepage
repositoryhttps://github.com/neonphog/tokio_safe_block_on
max_upload_size
id232646
size23,112
David Braden (neonphog)

documentation

https://docs.rs/tokio_safe_block_on

README

Crates.io Crates.io

tokio_safe_block_on

Provides the ability to execute async code from a sync context, without blocking a tokio core thread or busy looping the cpu.

Example

#[tokio::main(threaded_scheduler)]
async fn main() {
    // we need to ensure we are in the context of a tokio task
    tokio::task::spawn(async move {
        // some library api may take a sync callback
        // but we want to be able to execute async code
        (|| {
            let r = tokio_safe_block_on::tokio_safe_block_on(
                // async code to poll synchronously
                async move {
                    // simulate some async work
                    tokio::time::delay_for(
                        std::time::Duration::from_millis(2)
                    ).await;

                    // return our result
                    "test"
                },

                // timeout to allow async execution
                std::time::Duration::from_millis(10),
            ).unwrap();

            // note we get the result inline with no `await`
            assert_eq!("test", r);
        })()
    })
    .await
    .unwrap();
}
Commit count: 12

cargo fmt