Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add async spawn support #3235

Merged
merged 14 commits into from
Aug 31, 2024
Merged

Add async spawn support #3235

merged 14 commits into from
Aug 31, 2024

Conversation

kennykerr
Copy link
Collaborator

@kennykerr kennykerr commented Aug 30, 2024

Building on #3221 and #3213, this update concludes support for async implementations. You can now both consume and produce the four async interfaces defined by the Windows Runtime directly in Rust.

  • IAsyncAction
  • IAsyncOperation<T>
  • IAsyncActionWithProgress<P>
  • IAsyncOperationWithProgress<T, P>

As illustrated in #3221, if you happen to have a value ready to return, you can simply use the ready function as follows:

fn main() -> Result<()> {
    let ready = IAsyncOperation::ready(Ok(123));

    assert_eq!(ready.get()?, 123);

    Ok(())
}

If you need to spin up a background thread to wait for or calculate the value to return, you can use the spawn function as follows:

use windows::{core::*, Foundation::*};

fn main() -> Result<()> {
    let ready = IAsyncOperation::spawn(|| {
        std::thread::sleep(std::time::Duration::from_millis(1000)); // some lengthy operation
        Ok(123)
    });

    assert_eq!(ready.get()?, 123);

    Ok(())
}

While the ready implementations return immediately, the spawn implementations will take the closure and pass it by value to the Windows thread pool. This is far more efficient and scalable than creating a new thread each time spawn is called.

I have also included extensive tests for both ready and spawn implementations in this update.

@kennykerr
Copy link
Collaborator Author

Disabled the lib workflow as its proving unreliable.

@kennykerr kennykerr merged commit ef06753 into master Aug 31, 2024
78 checks passed
@kennykerr kennykerr deleted the async-spawn branch August 31, 2024 12:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant