57 lines
1.2 KiB
C++
57 lines
1.2 KiB
C++
#ifndef RUNCONTROLLABLETASK_H
|
|
#define RUNCONTROLLABLETASK_H
|
|
/** From answer by Hatter
|
|
*
|
|
* https://stackoverflow.com/questions/5423058/qfuture-that-can-be-cancelled-and-report-progress
|
|
*/
|
|
|
|
#include <QFutureInterface>
|
|
#include <QRunnable>
|
|
#include <QThreadPool>
|
|
#include "ControllableTask.h"
|
|
#include "TaskControl.h"
|
|
|
|
template <typename T>
|
|
class RunControllableTask : public QFutureInterface<T> , public QRunnable
|
|
{
|
|
public:
|
|
RunControllableTask(ControllableTask<T>* tsk) : task(tsk) { }
|
|
virtual ~RunControllableTask() { delete task; }
|
|
|
|
QFuture<T> start()
|
|
{
|
|
this->setRunnable(this);
|
|
this->reportStarted();
|
|
QFuture<T> future = this->future();
|
|
QThreadPool::globalInstance()->start(this, /*m_priority*/ 0);
|
|
return future;
|
|
}
|
|
|
|
void run()
|
|
{
|
|
if (this->isCanceled()) {
|
|
this->reportFinished();
|
|
return;
|
|
}
|
|
TaskControl control(this);
|
|
try {
|
|
result = this->task->run(control);
|
|
if (!this->isCanceled()) {
|
|
this->reportResult(result);
|
|
}
|
|
} catch (QException &e) {
|
|
QFutureInterfaceBase::reportException(e);
|
|
} catch (...) {
|
|
QUnhandledException ex;
|
|
QFutureInterfaceBase::reportException(ex);
|
|
}
|
|
|
|
this->reportFinished();
|
|
}
|
|
|
|
private:
|
|
T result;
|
|
ControllableTask<T> *task;
|
|
};
|
|
|
|
#endif // RUNCONTROLLABLETASK_H
|