pgLab/core/QueuedBackgroundTask.cpp
eelke 2705a3417b The MainWindow now uses a background task to load the catalog.
As the background task can't be cancelled yet only closing of the window
can block if the task is still running.
2017-12-28 07:23:20 +01:00

64 lines
1.1 KiB
C++

#include "QueuedBackgroundTask.h"
#include "ScopeGuard.h"
//void QueuedBackgroundTask::requestPause()
//{}
QueuedBackgroundTask::QueuedBackgroundTask(CompletionFunction on_completion)
: m_completionFunction(on_completion)
{
setAutoDelete(false);
}
QueuedBackgroundTask::~QueuedBackgroundTask()
{
cancel();
wait();
}
void QueuedBackgroundTask::cancel()
{
QMutexLocker lock(&stateMutex);
if (!m_finished)
m_canceled = true;
}
void QueuedBackgroundTask::wait()
{
QMutexLocker lock(&stateMutex);
if (!m_finished)
finished.wait(&stateMutex);
}
bool QueuedBackgroundTask::hasException() const
{
return doRunException != nullptr;
}
void QueuedBackgroundTask::rethrow()
{
std::rethrow_exception(doRunException);
}
void QueuedBackgroundTask::run()
{
SCOPE_EXIT {
m_finished = true;
QMutexLocker lock(&stateMutex);
finished.notify_all();
};
QMutexLocker lock(&stateMutex);
m_started = true;
if (!m_canceled) {
lock.unlock();
try {
doRun();
}
catch (...) {
doRunException = std::current_exception();
}
if (!m_canceled && m_completionFunction)
m_completionFunction(this);
}
}