- Extending Qt Creator Manual
- TaskingSolution
- TaskTree
- Extending Qt Creator Manual 13.0.0

# TaskTree Class

class Tasking::TaskTree

The TaskTree class runs an async task tree structure defined in a declarative way. More...

Header: | #include <solutions/tasking/tasktree.h>

- List of all members, including inherited members

Note: All functions in this class are reentrant.

## Public Functions

| TaskTree(const Tasking::Group &recipe)
| TaskTree()
virtual | ~TaskTree()
int | asyncCount() const
void | cancel()
bool | isRunning() const
void | onStorageDone(const Storage<StorageStruct> &storage, Handler &&handler)
void | onStorageSetup(const Storage<StorageStruct> &storage, Handler &&handler)
int | progressMaximum() const
int | progressValue() const
Tasking::DoneWith | runBlocking()
Tasking::DoneWith | runBlocking(const QFuture<void> &future)
void | setRecipe(const Tasking::Group &recipe)
void | start()
int | taskCount() const

## Signals

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

## Static Public Members

Tasking::DoneWith | runBlocking(const Tasking::Group &recipe, std::chrono::milliseconds timeout = std::chrono::milliseconds::max())
Tasking::DoneWith | runBlocking(const Tasking::Group &recipe, const QFuture<void> &future, std::chrono::milliseconds timeout = std::chrono::milliseconds::max())

## Detailed Description

Use the Tasking namespace to build extensible, declarative task tree structures that contain possibly asynchronous tasks, such as QProcess, NetworkQuery, or ConcurrentCall<ReturnType>. TaskTree structures enable you to create a sophisticated mixture of a parallel or sequential flow of tasks in the form of a tree and to run it any time later.

### Root Element and Tasks

The TaskTree has a mandatory Group root element, which may contain any number of tasks of various types, such as QProcessTask, NetworkQueryTask, or ConcurrentCallTask<ReturnType>:

     using namespace Tasking;

     const Group root {
         QProcessTask(...),
         NetworkQueryTask(...),
         ConcurrentCallTask<int>(...)
     };

     TaskTree *taskTree = new TaskTree(root);
     connect(taskTree, &TaskTree::done, ...);  // finish handler
     taskTree->start();

The task tree above has a top level element of the Group type that contains tasks of the QProcessTask, NetworkQueryTask, and ConcurrentCallTask<int> type. After taskTree->start() is called, the tasks are run in a chain, starting with QProcessTask. When the QProcessTask finishes successfully, the NetworkQueryTask task is started. Finally, when the network task finishes successfully, the ConcurrentCallTask<int> task is started.

When the last running task finishes with success, the task tree is considered to have run successfully and the done() signal is emitted with DoneWith::Success. When a task finishes with an error, the execution of the task tree is stopped and the remaining tasks are skipped. The task tree finishes with an error and sends the TaskTree::done() signal with DoneWith::Error.

### Groups

The parent of the Group sees it as a single task. Like other tasks, the group can be started and it can finish with success or an error. The Group elements can be nested to create a tree structure:

     const Group root {
         Group {
             parallel,
             QProcessTask(...),
             ConcurrentCallTask<int>(...)
         },
         NetworkQueryTask(...)
     };

The example above differs from the first example in that the root element has a subgroup that contains the QProcessTask and ConcurrentCallTask<int>. The subgroup is a sibling element of the NetworkQueryTask in the root. The subgroup contains an additional parallel element that instructs its Group to execute its tasks in parallel.

So, when the tree above is started, the QProcessTask and ConcurrentCallTask<int> start immediately and run in parallel. Since the root group doesn't contain a parallel element, its direct child tasks are run in sequence. Thus, the NetworkQueryTask starts when the whole subgroup finishes. The group is considered as finished when all its tasks have finished. The order in which the tasks finish is not relevant.

So, depending on which task lasts longer (QProcessTask or ConcurrentCallTask<int>), the following scenarios can take place:

Scenario 1 | Scenario 2
--- | ---
Root Group starts | Root Group starts
Sub Group starts | Sub Group starts
QProcessTask starts | QProcessTask starts
ConcurrentCallTask<int> starts | ConcurrentCallTask<int> starts
... | ...
QProcessTask finishes | ConcurrentCallTask<int> finishes
... | ...
ConcurrentCallTask<int> finishes | QProcessTask finishes
Sub Group finishes | Sub Group finishes
NetworkQueryTask starts | NetworkQueryTask starts
... | ...
NetworkQueryTask finishes | NetworkQueryTask finishes
Root Group finishes | Root Group finishes

The differences between the scenarios are marked with bold. Three dots mean that an unspecified amount of time passes between previous and next events (a task or tasks continue to run). No dots between events means that they occur synchronously.

The presented scenarios assume that all tasks run successfully. If a task fails during execution, the task tree finishes with an error. In particular, when QProcessTask finishes with an error while ConcurrentCallTask<int> is still being executed, the ConcurrentCallTask<int> is automatically canceled, the subgroup finishes with an error, the NetworkQueryTask is skipped, and the tree finishes with an error.

### Task Types

Each task type is associated with its corresponding task class that executes the task. For example, a QProcessTask inside a task tree is associated with the QProcess class that executes the process. The associated objects are automatically created, started, and destructed exclusively by the task tree at the appropriate time.

If a root group consists of five sequential QProcessTask tasks, and the task tree executes the group, it creates an instance of QProcess for the first QProcessTask and starts it. If the QProcess instance finishes successfully, the task tree destructs it and creates a new QProcess instance for the second QProcessTask, and so on. If the first task finishes with an error, the task tree stops creating QProcess instances, and the root group finishes with an error.

The following table shows examples of task types and their corresponding task classes:

Task Type (Tasking Namespace) | Associated Task Class | Brief Description
--- | --- | ---
QProcessTask | QProcess | Starts process.
ConcurrentCallTask<ReturnType> | Tasking::ConcurrentCall<ReturnType> | Starts asynchronous task, runs in separate thread.
TaskTreeTask | Tasking::TaskTree | Starts nested task tree.
NetworkQueryTask | NetworkQuery | Starts network download.

### Task Handlers

Use Task handlers to set up a task for execution and to enable reading the output data from the task when it finishes with success or an error.

#### Task's Start Handler

When a corresponding task class object is created and before it's started, the task tree invokes an optionally user-provided setup handler. The setup handler should always take a reference to the associated task class object:

     const auto onSetup = [](QProcess &process) {
         process.setCommand({"sleep", {"3"}});
     };
     const Group root {
         QProcessTask(onSetup)
     };

You can modify the passed QProcess in the setup handler, so that the task tree can start the process according to your configuration. You should not call `process.start();` in the setup handler, as the task tree calls it when needed. The setup handler is optional. When used, it must be the first argument of the task's constructor.

Optionally, the setup handler may return a SetupResult. The returned SetupResult influences the further start behavior of a given task. The possible values are:

SetupResult Value | Brief Description
--- | ---
Continue | The task will be started normally. This is the default behavior when the setup handler doesn't return SetupResult (that is, its return type is void).
StopWithSuccess | The task won't be started and it will report success to its parent.
StopWithError | The task won't be started and it will report an error to its parent.

This is useful for running a task only when a condition is met and the data needed to evaluate this condition is not known until previously started tasks finish. In this way, the setup handler dynamically decides whether to start the corresponding task normally or skip it and report success or an error. For more information about inter-task data exchange, see Storage.

#### Task's Done Handler

When a running task finishes, the task tree invokes an optionally provided done handler. The handler should always take a `const` reference to the associated task class object:

     const auto onSetup = [](QProcess &process) {
         process.setCommand({"sleep", {"3"}});
     };
     const auto onDone = [](const QProcess &process, DoneWith result) {
         if (result == DoneWith::Success)
             qDebug() << "Success" << process.cleanedStdOut();
         else
             qDebug() << "Failure" << process.cleanedStdErr();
     };
     const Group root {
         QProcessTask(onSetup, onDone)
     };

The done handler may collect output data from QProcess, and store it for further processing or perform additional actions.

Note: If the task setup handler returns StopWithSuccess or StopWithError, the done handler is not invoked.

### Group Handlers

Similarly to task handlers, group handlers enable you to set up a group to execute and to apply more actions when the whole group finishes with success or an error.

#### Group's Start Handler

The task tree invokes the group start handler before it starts the child tasks. The group handler doesn't take any arguments:

     const auto onSetup = [] {
         qDebug() << "Entering the group";
     };
     const Group root {
         onGroupSetup(onSetup),
         QProcessTask(...)
     };

The group setup handler is optional. To define a group setup handler, add an onGroupSetup() element to a group. The argument of onGroupSetup() is a user handler. If you add more than one onGroupSetup() element to a group, an assert is triggered at runtime that includes an error message.

Like the task's start handler, the group start handler may return SetupResult. The returned SetupResult value affects the start behavior of the whole group. If you do not specify a group start handler or its return type is void, the default group's action is SetupResult::Continue, so that all tasks are started normally. Otherwise, when the start handler returns SetupResult::StopWithSuccess or SetupResult::StopWithError, the tasks are not started (they are skipped) and the group itself reports success or failure, depending on the returned value, respectively.

     const Group root {
         onGroupSetup([] { qDebug() << "Root setup"; }),
         Group {
             onGroupSetup([] { qDebug() << "Group 1 setup"; return SetupResult::Continue; }),
             QProcessTask(...) // Process 1
         },
         Group {
             onGroupSetup([] { qDebug() << "Group 2 setup"; return SetupResult::StopWithSuccess; }),
             QProcessTask(...) // Process 2
         },
         Group {
             onGroupSetup([] { qDebug() << "Group 3 setup"; return SetupResult::StopWithError; }),
             QProcessTask(...) // Process 3
         },
         QProcessTask(...) // Process 4
     };

In the above example, all subgroups of a root group define their setup handlers. The following scenario assumes that all started processes finish with success:

Scenario | Comment
--- | ---
Root Group starts | Doesn't return SetupResult, so its tasks are executed.
Group 1 starts | Returns Continue, so its tasks are executed.
Process 1 starts |
... | ...
Process 1 finishes (success) |
Group 1 finishes (success) |
Group 2 starts | Returns StopWithSuccess, so Process 2 is skipped and Group 2 reports success.
Group 2 finishes (success) |
Group 3 starts | Returns StopWithError, so Process 3 is skipped and Group 3 reports an error.
Group 3 finishes (error) |
Root Group finishes (error) | Group 3, which is a direct child of the root group, finished with an error, so the root group stops executing, skips Process 4, which has not started yet, and reports an error.

#### Groups's Done Handler

A Group's done handler is executed after the successful or failed execution of its tasks. The final value reported by the group depends on its Workflow Policy. The handler can apply other necessary actions. The done handler is defined inside the onGroupDone() element of a group. It may take the optional DoneWith argument, indicating the successful or failed execution:

     const Group root {
         onGroupSetup([] { qDebug() << "Root setup"; }),
         QProcessTask(...),
         onGroupDone([](DoneWith result) {
             if (result == DoneWith::Success)
                 qDebug() << "Root finished with success";
             else
                 qDebug() << "Root finished with an error";
         })
     };

The group done handler is optional. If you add more than one onGroupDone() to a group, an assert is triggered at runtime that includes an error message.

Note: Even if the group setup handler returns StopWithSuccess or StopWithError, the group's done handler is invoked. This behavior differs from that of task done handler and might change in the future.

### Other Group Elements

A group can contain other elements that describe the processing flow, such as the execution mode or workflow policy. It can also contain storage elements that are responsible for collecting and sharing custom common data gathered during group execution.

#### Execution Mode

The execution mode element in a Group specifies how the direct child tasks of the Group are started. The most common execution modes are sequential and parallel. It's also possible to specify the limit of tasks running in parallel by using the parallelLimit() function.

In all execution modes, a group starts tasks in the oder in which they appear.

If a child of a group is also a group, the child group runs its tasks according to its own execution mode.

#### Workflow Policy

The workflow policy element in a Group specifies how the group should behave when any of its direct child's tasks finish. For a detailed description of possible policies, refer to WorkflowPolicy.

If a child of a group is also a group, the child group runs its tasks according to its own workflow policy.

#### Storage

Use the Storage element to exchange information between tasks. Especially, in the sequential execution mode, when a task needs data from another, already finished task, before it can start. For example, a task tree that copies data by reading it from a source and writing it to a destination might look as follows:

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

     static Group copyRecipe(const QString &source, const QString &destination)
     {
         struct CopyStorage { // [1] custom inter-task struct
             QByteArray content; // [2] custom inter-task data
         };

         // [3] instance of custom inter-task struct manageable by task tree
         const Storage<CopyStorage> storage;

         const auto onLoaderSetup = [source](ConcurrentCall<QByteArray> &async) {
             async.setConcurrentCallData(&load, source);
         };
         // [4] runtime: task tree activates the instance from [7] before invoking handler
         const auto onLoaderDone = [storage](const ConcurrentCall<QByteArray> &async) {
             storage->content = async.result(); // [5] loader stores the result in storage
         };

         // [4] runtime: task tree activates the instance from [7] before invoking handler
         const auto onSaverSetup = [storage, destination](ConcurrentCall<void> &async) {
             const QByteArray content = storage->content; // [6] saver takes data from storage
             async.setConcurrentCallData(&save, destination, content);
         };
         const auto onSaverDone = [](const ConcurrentCall<void> &async) {
             qDebug() << "Save done successfully";
         };

         const Group root {
             // [7] runtime: task tree creates an instance of CopyStorage when root is entered
             storage,
             ConcurrentCallTask<QByteArray>(onLoaderSetup, onLoaderDone, CallDoneIf::Success),
             ConcurrentCallTask<void>(onSaverSetup, onSaverDone, CallDoneIf::Success)
         };
         return root;
     }

     const QString source = ...;
     const QString destination = ...;
     TaskTree taskTree(copyRecipe(source, destination));
     connect(&taskTree, &TaskTree::done,
             &taskTree, [](DoneWith result) {
         if (result == DoneWith::Success)
             qDebug() << "The copying finished successfully.";
     });
     tasktree.start();

In the example above, the inter-task data consists of a QByteArray content variable [2] enclosed in a `CopyStorage` custom struct [1]. If the loader finishes successfully, it stores the data in a `CopyStorage::content` variable [5]. The saver then uses the variable to configure the saving task [6].

To enable a task tree to manage the `CopyStorage` struct, an instance of Storage<`CopyStorage>` is created [3]. If a copy of this object is inserted as the group's child item [7], an instance of the `CopyStorage` struct is created dynamically when the task tree enters this group. When the task tree leaves this group, the existing instance of the `CopyStorage` struct is destructed as it's no longer needed.

If several task trees holding a copy of the common Storage<`CopyStorage>` instance run simultaneously (including the case when the task trees are run in different threads), each task tree contains its own copy of the `CopyStorage` struct.

You can access `CopyStorage` from any handler in the group with a storage object. This includes all handlers of all descendant tasks of the group with a storage object. To access the custom struct in a handler, pass the copy of the Storage<`CopyStorage>` object to the handler (for example, in a lambda capture) [4].

When the task tree invokes a handler in a subtree containing the storage [7], the task tree activates its own `CopyStorage` instance inside the Storage<`CopyStorage>` object. Therefore, the `CopyStorage` struct may be accessed only from within the handler body. To access the currently active `CopyStorage` from within Storage<`CopyStorage>`, use the Storage::operator->(), Storage::operator*(), or Storage::activeStorage() method.

The following list summarizes how to employ a Storage object into the task tree:

1. Define the custom structure `MyStorage` with custom data [1], [2]
2. Create an instance of the Storage<`MyStorage>` storage [3]
3. Pass the Storage<`MyStorage>` instance to handlers [4]
4. Access the `MyStorage` instance in handlers [5], [6]
5. Insert the Storage<`MyStorage>` instance into a group [7]

### TaskTree class

TaskTree executes the tree structure of asynchronous tasks according to the recipe described by the Group root element.

As TaskTree is also an asynchronous task, it can be a part of another TaskTree. To place a nested TaskTree inside another TaskTree, insert the TaskTreeTask element into another Group element.

TaskTree reports progress of completed tasks when running. The progress value is increased when a task finishes or is skipped or canceled. When TaskTree is finished and the TaskTree::done() signal is emitted, the current value of the progress equals the maximum progress value. Maximum progress equals the total number of asynchronous tasks in a tree. A nested TaskTree is counted as a single task, and its child tasks are not counted in the top level tree. Groups themselves are not counted as tasks, but their tasks are counted. Sync tasks are not asynchronous, so they are not counted as tasks.

To set additional initial data for the running tree, modify the storage instances in a tree when it creates them by installing a storage setup handler:

     Storage<CopyStorage> storage;
     const Group root = ...; // storage placed inside root's group and inside handlers
     TaskTree taskTree(root);
     auto initStorage = [](CopyStorage &storage) {
         storage.content = "initial content";
     };
     taskTree.onStorageSetup(storage, initStorage);
     taskTree.start();

When the running task tree creates a `CopyStorage` instance, and before any handler inside a tree is called, the task tree calls the initStorage handler, to enable setting up initial data of the storage, unique to this particular run of taskTree.

Similarly, to collect some additional result data from the running tree, read it from storage instances in the tree when they are about to be destroyed. To do this, install a storage done handler:

     Storage<CopyStorage> storage;
     const Group root = ...; // storage placed inside root's group and inside handlers
     TaskTree taskTree(root);
     auto collectStorage = [](const CopyStorage &storage) {
         qDebug() << "final content" << storage.content;
     };
     taskTree.onStorageDone(storage, collectStorage);
     taskTree.start();

When the running task tree is about to destroy a `CopyStorage` instance, the task tree calls the collectStorage handler, to enable reading the final data from the storage, unique to this particular run of taskTree.

### Task Adapters

To extend a TaskTree with a new task type, implement a simple adapter class derived from the TaskAdapter class template. The following class is an adapter for a single shot timer, which may be considered as a new asynchronous task:

     class TimerTaskAdapter : public TaskAdapter<QTimer>
     {
     public:
         TimerTaskAdapter() {
             task()->setSingleShot(true);
             task()->setInterval(1000);
             connect(task(), &QTimer::timeout, this, [this] { emit done(DoneResult::Success); });
         }
     private:
         void start() final { task()->start(); }
     };

     using TimerTask = CustomTask<TimerTaskAdapter>;

You must derive the custom adapter from the TaskAdapter class template instantiated with a template parameter of the class implementing a running task. The code above uses QTimer to run the task. This class appears later as an argument to the task's handlers. The instance of this class parameter automatically becomes a member of the TaskAdapter template, and is accessible through the TaskAdapter::task() method. The constructor of `TimerTaskAdapter` initially configures the QTimer object and connects to the QTimer::timeout() signal. When the signal is triggered, `TimerTaskAdapter` emits the TaskInterface::done(DoneResult::Success) signal to inform the task tree that the task finished successfully. If it emits TaskInterface::done(DoneResult::Error), the task finished with an error. The TaskAdapter::start() method starts the timer.

To make QTimer accessible inside TaskTree under the `TimerTask` name, define `TimerTask` to be an alias to the CustomTask<`TimerTaskAdapter>`. `TimerTask` becomes a new custom task type, using `TimerTaskAdapter`.

The new task type is now registered, and you can use it in TaskTree:

     const auto onSetup = [](QTimer &task) { task.setInterval(2000); };
     const auto onDone = [] { qDebug() << "timer triggered"; };
     const Group root {
         TimerTask(onSetup, onDone)
     };

When a task tree containing the root from the above example is started, it prints a debug message within two seconds and then finishes successfully.

Note: The class implementing the running task should have a default constructor, and objects of this class should be freely destructible. It should be allowed to destroy a running object, preferably without waiting for the running task to finish (that is, safe non-blocking destructor of a running task). To achieve a non-blocking destruction of a task that has a blocking destructor, consider using the optional `Deleter` template parameter of the TaskAdapter.

## Member Function Documentation

### TaskTree::TaskTree(const Tasking::Group &recipe)

This is an overloaded function.

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

See also setRecipe() and start().

### TaskTree::TaskTree()

Constructs an empty task tree. 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().

### `[signal]` void TaskTree::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().

### `[signal]` void TaskTree::done(Tasking::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().

### `[signal]` void TaskTree::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().

### `[signal]` void TaskTree::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().

### `[virtual]` TaskTree::~TaskTree()

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 TaskTree::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().

### void TaskTree::cancel()

Cancels the execution of the running task tree.

Cancels all the running tasks immediately. All running tasks finish with an error, invoking their error handlers. All running groups dispatch their handlers according to their workflow policies, invoking their done handlers. 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 ~TaskTree().

### bool TaskTree::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 TaskTree::onStorageDone(const 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 = [](ConcurrentCall<QByteArray> &concurrent) {
         concurrent.setConcurrentCallData(&load, "foo.txt");
     };
     const auto onLoaderDone = [storage](const ConcurrentCall<QByteArray> &concurrent) {
         *storage = concurrent.result();
     };

     const Group root {
         storage,
         ConcurrentCallTask(onLoaderSetup, onLoaderDone, CallDoneIf::Success)
     };

     TaskTree 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 TaskTree::onStorageSetup(const 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](ConcurrentCall<QByteArray> &concurrent) {
         concurrent.setConcurrentCallData(&save, "foo.txt", *storage);
     };

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

     TaskTree 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 TaskTree::progressMaximum() const

Returns the maximum progressValue().

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

See also progressValue().

### int TaskTree::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().

### Tasking::DoneWith TaskTree::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().

### Tasking::DoneWith TaskTree::runBlocking(const QFuture<void> &future)

This function overloads runBlocking().

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

### `[static]` Tasking::DoneWith TaskTree::runBlocking(const Tasking::Group &recipe, std::chrono::milliseconds timeout = std::chrono::milliseconds::max())

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

The optionally provided timeout is used to cancel the tree automatically after timeout milliseconds have passed.

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]` Tasking::DoneWith TaskTree::runBlocking(const Tasking::Group &recipe, const QFuture<void> &future, std::chrono::milliseconds timeout = std::chrono::milliseconds::max())

This function overloads runBlocking(const Group &recipe, milliseconds timeout).

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

### void TaskTree::setRecipe(const Tasking::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 TaskTree(const Tasking::Group &recipe) and start().

### void TaskTree::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 or QCoreApplication or one of its subclasses running (or about to be run) when calling this method.

See also TaskTree(const Tasking::Group &), setRecipe(), isRunning(), and cancel().

### int TaskTree::taskCount() const

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

Note: The returned number doesn't include Sync 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().