From 71424d0fe48bf4cf62626f1e36e2e5f861cb018d Mon Sep 17 00:00:00 2001 From: dec05eba Date: Sat, 31 Oct 2020 17:02:09 +0100 Subject: Matrix: cancel tasks when leaving chat page. This fixes delay in chat page close sometimes --- include/AsyncTask.hpp | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 include/AsyncTask.hpp (limited to 'include') diff --git a/include/AsyncTask.hpp b/include/AsyncTask.hpp new file mode 100644 index 0000000..0d9c453 --- /dev/null +++ b/include/AsyncTask.hpp @@ -0,0 +1,65 @@ +#pragma once + +#include "Program.hpp" +#include +#include + +namespace QuickMedia { + template + class AsyncTask { + public: + using CallbackFunc = std::function; + + AsyncTask() = default; + + AsyncTask(CallbackFunc callback_func) { + std::promise promise; + future = promise.get_future(); + thread = std::thread(&AsyncTask::thread_handler, this, std::move(promise), std::move(callback_func)); + } + + AsyncTask& operator=(CallbackFunc callback_func) { + cancel(); + std::promise promise; + future = promise.get_future(); + thread = std::thread(&AsyncTask::thread_handler, this, std::move(promise), std::move(callback_func)); + return *this; + } + + ~AsyncTask() { + cancel(); + } + + bool valid() { + return future.valid(); + } + + bool ready() { + return future.valid() && future.wait_for(std::chrono::seconds(0)) == std::future_status::ready; + } + + T get() { + thread.join(); + return future.get(); + } + + void cancel() { + if(valid()) { + program_kill_in_thread(thread.get_id()); + get(); + } + } + private: + void thread_handler(std::promise &&promise, CallbackFunc callback_func) { + if constexpr(std::is_same::value) { + callback_func(); + promise.set_value(); + } else { + promise.set_value(callback_func()); + } + } + private: + std::thread thread; + std::future future; + }; +} \ No newline at end of file -- cgit v1.2.3