- Extending Qt Creator Manual
- TaskTree
- QTaskTree
- Extending Qt Creator Manual 19.0.0-beta2

# QTaskTree Class

The QTaskTree class runs the tree of asynchronous tasks defined in a declarative way. More...

Header: | `#include <qtasktree.h>`
Inherits: | QObject

- List of all members, including inherited members

Note: All functions in this class are reentrant.

## Public Functions

| QTaskTree(QObject *parent = nullptr)
| QTaskTree(const QtTaskTree::Group &recipe, QObject *parent = nullptr)
virtual | ~QTaskTree() override
int | asyncCount() const
void | cancel()
bool | isRunning() const
void | onStorageDone(const QtTaskTree::Storage<StorageStruct> &storage, Handler &&handler)
void | onStorageSetup(const QtTaskTree::Storage<StorageStruct> &storage, Handler &&handler)
int | progressMaximum() const
int | progressValue() const
QtTaskTree::DoneWith | runBlocking()
QtTaskTree::DoneWith | runBlocking(const QFuture<void> &future)
void | setRecipe(const QtTaskTree::Group &recipe)
void | start()
int | taskCount() const

## Signals

void | asyncCountChanged(int count)
void | done(QtTaskTree::DoneWith result)
void | progressValueChanged(int value)
void | started()

## Static Public Members

QtTaskTree::DoneWith | runBlocking(const QtTaskTree::Group &recipe)
QtTaskTree::DoneWith | runBlocking(const QtTaskTree::Group &recipe, const QFuture<void> &future)

## Detailed Description

The description on what the task tree should do is passed via recipe.

## Member Function Documentation

### QTaskTree::QTaskTree(QObject *parent = nullptr)

Constructs an empty task tree with a given parent. Use setRecipe() to pass a declarative description on how the task tree should execute the tasks and how it should handle the finished tasks.

Starting an empty task tree is no-op and the relevant warning message is issued.

See also setRecipe() and start().

### QTaskTree::QTaskTree(const QtTaskTree::Group &recipe, QObject *parent = nullptr)

Constructs a task tree with a given recipe and parent. After the task tree is started, it executes the tasks contained inside the recipe and handles finished tasks according to the passed description.

This is an overloaded function.

See also setRecipe() and start().

### `[override virtual noexcept]` QTaskTree::~QTaskTree()

Destroys the task tree.

When the task tree is running while being destructed, it cancels all the running tasks immediately. In this case, no handlers are called, not even the groups' and tasks' done handlers or onStorageDone() handlers. The task tree also doesn't emit any signals from the destructor, not even done() or progressValueChanged() signals. This behavior may always be relied on. It is completely safe to destruct the running task tree.

It's a usual pattern to destruct the running task tree. It's guaranteed that the destruction will run quickly, without having to wait for the currently running tasks to finish, provided that the used tasks implement their destructors in a non-blocking way.

Note: Do not call the destructor directly from any of the running task's handlers or task tree's signals. In these cases, use deleteLater() instead.

See also cancel().

### int QTaskTree::asyncCount() const

Returns the current real count of asynchronous chains of invocations.

The returned value indicates how many times the control returns to the caller's event loop while the task tree is running. Initially, this value is `0`. If the execution of the task tree finishes fully synchronously, this value remains `0`. If the task tree contains any asynchronous tasks that are successfully started during a call to start(), this value is bumped to `1` just before the call to start() finishes. Later, when any asynchronous task finishes and any possible continuations are started, this value is bumped again. The bumping continues until the task tree finishes. When the task tree emits the done() signal, the bumping stops. The asyncCountChanged() signal is emitted on every bump of this value.

See also asyncCountChanged().

### `[signal]` void QTaskTree::asyncCountChanged(int count)

This signal is emitted when the running task tree is about to return control to the caller's event loop. When the task tree is started, this signal is emitted with count value of `0`, and emitted later on every asyncCount() value bump with an updated count value. Every signal sent (except the initial one with the value of `0`) guarantees that the task tree is still running asynchronously after the emission.

See also asyncCount().

### void QTaskTree::cancel()

Cancels the execution of the running task tree.

Cancels all running tasks immediately. All running tasks and groups finish with an error, invoking their done handlers with DoneWith::Cancel. The storages' onStorageDone() handlers are invoked, too. The progressValueChanged() signals are also being sent. This behavior may always be relied on.

The cancel() function is executed synchronously, so that after a call to cancel() all running tasks are finished and the tree is already canceled. It's guaranteed that cancel() will run quickly, without any blocking wait for the currently running tasks to finish, provided the used tasks implement their destructors in a non-blocking way.

When the task tree is empty, that is, constructed with a default constructor, a call to cancel() is no-op and the relevant warning message is issued.

Otherwise, when the task tree wasn't started, a call to cancel() is ignored.

Note: Do not call this function directly from any of the running task's handlers or task tree's signals.

See also ~QTaskTree().

### `[signal]` void QTaskTree::done(QtTaskTree::DoneWith result)

This signal is emitted when the task tree finished, passing the final result of the execution. The task tree neither calls any handler, nor emits any signal anymore after this signal was emitted.

Note: Do not delete the task tree directly from this signal's handler. Use deleteLater() instead.

See also started().

### bool QTaskTree::isRunning() const

Returns `true` if the task tree is currently running; otherwise returns `false`.

See also start() and cancel().

### template <typename StorageStruct, typename Handler> void QTaskTree::onStorageDone(const QtTaskTree::Storage<StorageStruct> &storage, Handler &&handler)

Installs a storage done handler for the storage to retrieve the final data dynamically from the running task tree.

The `StorageHandler` takes a `const` reference to the `StorageStruct` instance:

     static QByteArray load(const QString &fileName) { ... }

     Storage<QByteArray> storage;

     const auto onLoaderSetup = [](QThreadFunction<QByteArray> &task) {
         task.setThreadFunctionData(&load, "foo.txt");
     };
     const auto onLoaderDone = [storage](const QThreadFunction<QByteArray> &task) {
         *storage = task.result();
     };

     const Group root {
         storage,
         QThreadFunctionTask(onLoaderSetup, onLoaderDone, CallDone::OnSuccess)
     };

     QTaskTree taskTree(root);
     auto collectStorage = [](const QByteArray &storage){
         qDebug() << "final content" << storage;
     };
     taskTree.onStorageDone(storage, collectStorage);
     taskTree.start();

When the running task tree is about to leave a Group where the storage is placed in, it destructs a `StorageStruct` instance. Just before the `StorageStruct` instance is destructed, and after all possible handlers from this group were called, the task tree invokes the passed handler. This enables reading the final content of the given storage dynamically and processing it further outside of the task tree.

This handler is called also when the running tree is canceled. However, it's not called when the running tree is destructed.

See also onStorageSetup().

### template <typename StorageStruct, typename Handler> void QTaskTree::onStorageSetup(const QtTaskTree::Storage<StorageStruct> &storage, Handler &&handler)

Installs a storage setup handler for the storage to pass the initial data dynamically to the running task tree.

The `StorageHandler` takes a reference to the `StorageStruct` instance:

     static void save(const QString &fileName, const QByteArray &array) { ... }

     Storage<QByteArray> storage;

     const auto onSaverSetup = [storage](QThreadFunction<QByteArray> &task) {
         task.setThreadFunctionData(&save, "foo.txt", *storage);
     };

     const Group root {
         storage,
         QThreadFunctionTask(onSaverSetup)
     };

     QTaskTree taskTree(root);
     auto initStorage = [](QByteArray &storage){
         storage = "initial content";
     };
     taskTree.onStorageSetup(storage, initStorage);
     taskTree.start();

When the running task tree enters a Group where the storage is placed in, it creates a `StorageStruct` instance, ready to be used inside this group. Just after the `StorageStruct` instance is created, and before any handler of this group is called, the task tree invokes the passed handler. This enables setting up initial content for the given storage dynamically. Later, when any group's handler is invoked, the task tree activates the created and initialized storage, so that it's available inside any group's handler.

See also onStorageDone().

### int QTaskTree::progressMaximum() const

Returns the maximum progressValue().

Note: Currently, it's the same as taskCount(). This might change in the future.

See also progressValue().

### int QTaskTree::progressValue() const

Returns the current progress value, which is between the `0` and progressMaximum().

The returned number indicates how many tasks have been already finished, canceled, or skipped while the task tree is running. When the task tree is started, this number is set to `0`. When the task tree is finished, this number always equals progressMaximum().

See also progressMaximum() and progressValueChanged().

### `[signal]` void QTaskTree::progressValueChanged(int value)

This signal is emitted when the running task tree finished, canceled, or skipped some tasks. The value gives the current total number of finished, canceled or skipped tasks. When the task tree is started, and after the started() signal was emitted, this signal is emitted with an initial value of `0`. When the task tree is about to finish, and before the done() signal is emitted, this signal is emitted with the final value of progressMaximum().

See also progressValue() and progressMaximum().

### QtTaskTree::DoneWith QTaskTree::runBlocking()

Executes a local event loop with QEventLoop::ExcludeUserInputEvents and starts the task tree.

Returns DoneWith::Success if the task tree finished successfully; otherwise returns DoneWith::Error.

Note: Avoid using this method from the main thread. Use asynchronous start() instead. This method is to be used in non-main threads or in auto tests.

See also start().

### `[static]` QtTaskTree::DoneWith QTaskTree::runBlocking(const QtTaskTree::Group &recipe)

Constructs a temporary task tree using the passed recipe and runs it blocking.

Returns DoneWith::Success if the task tree finished successfully; otherwise returns DoneWith::Error.

Note: Avoid using this method from the main thread. Use asynchronous start() instead. This method is to be used in non-main threads or in auto tests.

See also start().

### QtTaskTree::DoneWith QTaskTree::runBlocking(const QFuture<void> &future)

The passed future is used for listening to the cancel event. When the task tree is canceled, this method cancels the passed future.

This function overloads QTaskTree::runBlocking().

### `[static]` QtTaskTree::DoneWith QTaskTree::runBlocking(const QtTaskTree::Group &recipe, const QFuture<void> &future)

The passed future is used for listening to the cancel event. When the task tree is canceled, this method cancels the passed future.

This function overloads QTaskTree::runBlocking(const Group &recipe).

### void QTaskTree::setRecipe(const QtTaskTree::Group &recipe)

Sets a given recipe for the task tree. After the task tree is started, it executes the tasks contained inside the recipe and handles finished tasks according to the passed description.

Note: When called for a running task tree, the call is ignored.

See also QTaskTree(const QtTaskTree::Group &recipe, QObject *parent = nullptr) and start().

### void QTaskTree::start()

Starts the task tree.

Use setRecipe() or the constructor to set the declarative description according to which the task tree will execute the contained tasks and handle finished tasks.

When the task tree is empty, that is, constructed with a default constructor, a call to start() is no-op and the relevant warning message is issued.

Otherwise, when the task tree is already running, a call to start() is ignored and the relevant warning message is issued.

Otherwise, the task tree is started.

The started task tree may finish synchronously, for example when the main group's start handler returns SetupResult::StopWithError. For this reason, the connection to the done signal should be established before calling start(). Use isRunning() in order to detect whether the task tree is still running after a call to start().

The task tree implementation relies on the running event loop. Make sure you have a QEventLoop, QCoreApplication, or one of its subclasses running (or about to be run) when calling this method.

See also QTaskTree(const QtTaskTree::Group &recipe, QObject *parent = nullptr), setRecipe(), isRunning(), and cancel().

### `[signal]` void QTaskTree::started()

This signal is emitted when the task tree is started. The emission of this signal is followed synchronously by the progressValueChanged() signal with an initial `0` value.

See also start() and done().

### int QTaskTree::taskCount() const

Returns the number of asynchronous tasks contained in the stored recipe.

Note: The returned number doesn't include QSyncTask tasks.

Note: Any task or group that was set up using withTimeout() increases the total number of tasks by `1`.

See also setRecipe() and progressMaximum().