/*** Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved. File: AsyncRunnable.hpp Date: 2021-11-2 Author: Reece ***/ #pragma once namespace Aurora::Async { class IAsyncRunnable { public: virtual float GetPrio() { return 0.5f; }; virtual void RunAsync() = 0; virtual void CancelAsync() {} }; class AsyncFuncRunnable : public IAsyncRunnable { public: AuFunction callback; AuFunction fail; AuThreadPrimitives::SpinLock lock; AsyncFuncRunnable(AuFunction &&callback) : callback(AuMove(callback)) {} AsyncFuncRunnable(AuFunction &&callback, AuFunction &&fail) : callback(AuMove(callback)), fail(AuMove(fail)) {} AsyncFuncRunnable(const AuFunction &callback) : callback(callback) {} AsyncFuncRunnable(const AuFunction &callback, const AuFunction &fail) : callback(callback), fail(fail) {} void RunAsync() override { AU_LOCK_GUARD(lock); SysAssertDbgExp(callback, "Missing callback std::function"); try { callback(); } catch (...) { Debug::PrintError(); } fail = {}; callback = {}; } void CancelAsync() override { AU_LOCK_GUARD(lock); if (fail) { try { fail(); } catch (...) { Debug::PrintError(); } } fail = {}; callback = {}; } }; }