feat: Add JoinHandle::abort() (#2877)

Co-authored-by: Lucas Nogueira <lucas@tauri.studio>
This commit is contained in:
Chaoqian Xu 2021-11-13 09:22:26 +08:00 committed by GitHub
parent 3de67cb341
commit ad16975938
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 0 deletions

View File

@ -0,0 +1,5 @@
---
"tauri": patch
---
Added `abort` method to `tauri::async_runtime::JoinHandle`.

View File

@ -35,6 +35,17 @@ static RUNTIME: OnceCell<Runtime> = OnceCell::new();
#[derive(Debug)]
pub struct JoinHandle<T>(TokioJoinHandle<T>);
impl<T> JoinHandle<T> {
/// Abort the task associated with the handle.
///
/// Awaiting a cancelled task might complete as usual if the task was
/// already completed at the time it was cancelled, but most likely it
/// will fail with a cancelled `JoinError`.
pub fn abort(&self) {
self.0.abort();
}
}
impl<T> Future for JoinHandle<T> {
type Output = crate::Result<T>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
@ -108,4 +119,17 @@ mod tests {
let handle = handle();
assert_eq!(handle.block_on(async { 0 }), 0);
}
#[tokio::test]
async fn handle_abort() {
let handle = handle();
let join = handle.spawn(async { 5 });
join.abort();
if let crate::Error::JoinError(raw_box) = join.await.unwrap_err() {
let raw_error = raw_box.downcast::<tokio::task::JoinError>().unwrap();
assert!(raw_error.is_cancelled());
} else {
panic!("Abort did not result in the expected `JoinError`");
}
}
}