Skip to content

Commit 03e8399

Browse files
committed
[Rust] Add OwnedBackgroundTaskGuard for finishing background task automatically
1 parent fc2fc58 commit 03e8399

File tree

1 file changed

+39
-4
lines changed

1 file changed

+39
-4
lines changed

rust/src/background_task.rs

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,40 @@ use crate::string::*;
2424

2525
pub type Result<R> = result::Result<R, ()>;
2626

27+
/// An RAII guard for [`BackgroundTask`] to finish the task when dropped.
28+
pub struct OwnedBackgroundTaskGuard {
29+
pub(crate) task: Ref<BackgroundTask>,
30+
}
31+
32+
impl OwnedBackgroundTaskGuard {
33+
pub fn cancel(&mut self) {
34+
self.task.cancel();
35+
}
36+
37+
pub fn is_cancelled(&self) -> bool {
38+
self.task.is_cancelled()
39+
}
40+
41+
pub fn set_progress_text(&mut self, text: &str) {
42+
self.task.set_progress_text(text);
43+
}
44+
}
45+
46+
impl Drop for OwnedBackgroundTaskGuard {
47+
fn drop(&mut self) {
48+
self.task.finish();
49+
}
50+
}
51+
2752
/// A [`BackgroundTask`] does not actually execute any code, only act as a handler, primarily to query
2853
/// the status of the task, and to cancel the task.
2954
///
30-
/// If you are looking to execute code in the background consider using rusts threading API, or if you
31-
/// want the core to execute the task on a worker thread, use the [`crate::worker_thread`] API.
55+
/// If you are looking to execute code in the background, consider using rusts threading API, or if you
56+
/// want the core to execute the task on a worker thread, instead use the [`crate::worker_thread`] API.
3257
///
33-
/// NOTE: If you do not call [`BackgroundTask::finish`] or [`BackgroundTask::cancel`] the task will
34-
/// persist even _after_ it has been dropped.
58+
/// NOTE: If you do not call [`BackgroundTask::finish`] or [`BackgroundTask::cancel`], the task will
59+
/// persist even _after_ it has been dropped, use [`OwnedBackgroundTaskGuard`] to ensure the task is
60+
/// finished, see [`BackgroundTask::enter`] for usage.
3561
#[derive(PartialEq, Eq, Hash)]
3662
pub struct BackgroundTask {
3763
pub(crate) handle: *mut BNBackgroundTask,
@@ -52,6 +78,15 @@ impl BackgroundTask {
5278
unsafe { Ref::new(Self { handle }) }
5379
}
5480

81+
/// Creates a [`OwnedBackgroundTaskGuard`] that is responsible for finishing the background task
82+
/// once dropped. Because the status of a task does not dictate the underlying objects' lifetime,
83+
/// this can be safely done without requiring exclusive ownership.
84+
pub fn enter(&self) -> OwnedBackgroundTaskGuard {
85+
OwnedBackgroundTaskGuard {
86+
task: self.to_owned(),
87+
}
88+
}
89+
5590
pub fn can_cancel(&self) -> bool {
5691
unsafe { BNCanCancelBackgroundTask(self.handle) }
5792
}

0 commit comments

Comments
 (0)