summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibThreading/BackgroundAction.h
diff options
context:
space:
mode:
authorSpencer Dixon <spencercdixon@gmail.com>2021-07-02 10:34:19 -0400
committerAndreas Kling <kling@serenityos.org>2021-07-02 16:47:14 +0200
commit00f93b254547c6a63e58cfc46591f6db07cc6765 (patch)
tree89e9bdaeb565d1a76ead8a9d94002a286ab7ab39 /Userland/Libraries/LibThreading/BackgroundAction.h
parent4a3958c8ae16258071fa127eed7417dd07c41b5d (diff)
downloadserenity-00f93b254547c6a63e58cfc46591f6db07cc6765.zip
LibThreading: Add ability to cancel ongoing BackgroundActions
Handlers of the BackgroundAction are responsible for checking if the action has been cancelled and returning early.
Diffstat (limited to 'Userland/Libraries/LibThreading/BackgroundAction.h')
-rw-r--r--Userland/Libraries/LibThreading/BackgroundAction.h19
1 files changed, 15 insertions, 4 deletions
diff --git a/Userland/Libraries/LibThreading/BackgroundAction.h b/Userland/Libraries/LibThreading/BackgroundAction.h
index 9c40873a3c..2ac77d5758 100644
--- a/Userland/Libraries/LibThreading/BackgroundAction.h
+++ b/Userland/Libraries/LibThreading/BackgroundAction.h
@@ -39,16 +39,26 @@ class BackgroundAction final : public Core::Object
public:
static NonnullRefPtr<BackgroundAction<Result>> create(
- Function<Result()> action,
+ Function<Result(BackgroundAction&)> action,
Function<void(Result)> on_complete = nullptr)
{
return adopt_ref(*new BackgroundAction(move(action), move(on_complete)));
}
+ void cancel()
+ {
+ m_cancelled = true;
+ }
+
+ bool is_cancelled() const
+ {
+ return m_cancelled;
+ }
+
virtual ~BackgroundAction() { }
private:
- BackgroundAction(Function<Result()> action, Function<void(Result)> on_complete)
+ BackgroundAction(Function<Result(BackgroundAction&)> action, Function<void(Result)> on_complete)
: Core::Object(&background_thread())
, m_action(move(action))
, m_on_complete(move(on_complete))
@@ -56,7 +66,7 @@ private:
Locker locker(all_actions().lock());
all_actions().resource().enqueue([this] {
- m_result = m_action();
+ m_result = m_action(*this);
if (m_on_complete) {
Core::EventLoop::current().post_event(*this, make<Core::DeferredInvocationEvent>([this](auto&) {
m_on_complete(m_result.release_value());
@@ -69,7 +79,8 @@ private:
});
}
- Function<Result()> m_action;
+ bool m_cancelled { false };
+ Function<Result(BackgroundAction&)> m_action;
Function<void(Result)> m_on_complete;
Optional<Result> m_result;
};