AuroraRuntime/Source/Async/AsyncRunnable.hpp

75 lines
1.8 KiB
C++

/***
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<void()> callback;
AuFunction<void()> fail;
AuThreadPrimitives::SpinLock lock;
AsyncFuncRunnable(AuFunction<void()> &&callback) : callback(AuMove(callback))
{}
AsyncFuncRunnable(AuFunction<void()> &&callback, AuFunction<void()> &&fail) : callback(AuMove(callback)), fail(AuMove(fail))
{}
AsyncFuncRunnable(const AuFunction<void()> &callback) : callback(callback)
{}
AsyncFuncRunnable(const AuFunction<void()> &callback, const AuFunction<void()> &fail) : callback(callback), fail(fail)
{}
void RunAsync() override
{
AU_LOCK_GUARD(lock);
SysAssertDbgExp(callback, "Missing callback function");
try
{
callback();
}
catch (...)
{
Debug::PrintError();
}
fail = {};
callback = {};
}
void CancelAsync() override
{
AU_LOCK_GUARD(lock);
if (fail)
{
try
{
fail();
}
catch (...)
{
Debug::PrintError();
}
}
fail = {};
callback = {};
}
};
}