From ad16975938afc9e87747de5fdcb0f07fc2d24811 Mon Sep 17 00:00:00 2001 From: Chaoqian Xu Date: Sat, 13 Nov 2021 09:22:26 +0800 Subject: [PATCH] feat: Add JoinHandle::abort() (#2877) Co-authored-by: Lucas Nogueira --- .changes/join-handle-abort.md | 5 +++++ core/tauri/src/async_runtime.rs | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 .changes/join-handle-abort.md diff --git a/.changes/join-handle-abort.md b/.changes/join-handle-abort.md new file mode 100644 index 000000000..3e4d76229 --- /dev/null +++ b/.changes/join-handle-abort.md @@ -0,0 +1,5 @@ +--- +"tauri": patch +--- + +Added `abort` method to `tauri::async_runtime::JoinHandle`. diff --git a/core/tauri/src/async_runtime.rs b/core/tauri/src/async_runtime.rs index e63de1ef6..8d1148eea 100644 --- a/core/tauri/src/async_runtime.rs +++ b/core/tauri/src/async_runtime.rs @@ -35,6 +35,17 @@ static RUNTIME: OnceCell = OnceCell::new(); #[derive(Debug)] pub struct JoinHandle(TokioJoinHandle); +impl JoinHandle { + /// 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 Future for JoinHandle { type Output = crate::Result; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { @@ -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::().unwrap(); + assert!(raw_error.is_cancelled()); + } else { + panic!("Abort did not result in the expected `JoinError`"); + } + } }