BackgroundAction.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (c) 2019-2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  4. * Copyright (c) 2022, the SerenityOS developers.
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #pragma once
  9. #include <AK/Function.h>
  10. #include <AK/NonnullRefPtr.h>
  11. #include <AK/Optional.h>
  12. #include <AK/Queue.h>
  13. #include <LibCore/Event.h>
  14. #include <LibCore/EventLoop.h>
  15. #include <LibCore/Object.h>
  16. #include <LibThreading/Thread.h>
  17. namespace Threading {
  18. template<typename Result>
  19. class BackgroundAction;
  20. class BackgroundActionBase {
  21. template<typename Result>
  22. friend class BackgroundAction;
  23. private:
  24. BackgroundActionBase() = default;
  25. static void enqueue_work(Function<void()>);
  26. static Thread& background_thread();
  27. };
  28. template<typename Result>
  29. class BackgroundAction final : public Core::Object
  30. , private BackgroundActionBase {
  31. C_OBJECT(BackgroundAction);
  32. public:
  33. void cancel()
  34. {
  35. m_cancelled = true;
  36. }
  37. bool is_cancelled() const
  38. {
  39. return m_cancelled;
  40. }
  41. virtual ~BackgroundAction() = default;
  42. private:
  43. BackgroundAction(Function<Result(BackgroundAction&)> action, Function<void(Result)> on_complete)
  44. : Core::Object(&background_thread())
  45. , m_action(move(action))
  46. , m_on_complete(move(on_complete))
  47. {
  48. enqueue_work([this, origin_event_loop = &Core::EventLoop::current()] {
  49. m_result = m_action(*this);
  50. if (m_on_complete) {
  51. origin_event_loop->deferred_invoke([this] {
  52. m_on_complete(m_result.release_value());
  53. remove_from_parent();
  54. });
  55. origin_event_loop->wake();
  56. } else {
  57. this->remove_from_parent();
  58. }
  59. });
  60. }
  61. bool m_cancelled { false };
  62. Function<Result(BackgroundAction&)> m_action;
  63. Function<void(Result)> m_on_complete;
  64. Optional<Result> m_result;
  65. };
  66. }