KEMBAR78
Add async `spawn` support by kennykerr · Pull Request #3235 · microsoft/windows-rs · GitHub
Skip to content

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
@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