userver: userver/engine/task/task.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
task.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/engine/task/task.hpp
4/// @brief @copybrief engine::Task
5
6#include <userver/engine/task/task_base.hpp>
7
8USERVER_NAMESPACE_BEGIN
9
10namespace engine {
11
12/// @brief Asynchronous task that has a unique ownership of the payload.
13///
14/// See engine::TaskWithResult for a type that could return a value or
15/// report an exception from the payload.
16class [[nodiscard]] Task : public TaskBase {
17public:
18 /// @brief Default constructor
19 ///
20 /// Creates an invalid task.
22
23 /// @brief If the task is still valid and is not finished, cancels it and
24 /// waits until it finishes.
25 ~Task();
26
27 /// @brief Moves the other task into this, leaving the other in an invalid
28 /// state.
29 Task(Task&& other) noexcept;
30
31 /// @brief If this Task is still valid and is not finished, cancels it and
32 /// waits until it finishes before moving the other. Otherwise just moves the
33 /// other task into this, leaving the other in invalid state.
34 Task& operator=(Task&& other) noexcept;
35
36 Task(const Task&) = delete;
37 Task& operator=(const Task&) = delete;
38
39 /// @cond
40 // For internal use only.
41 impl::ContextAccessor* TryGetContextAccessor() noexcept;
42 /// @endcond
43
44protected:
45 /// @cond
46 // For internal use only.
47 explicit Task(impl::TaskContextHolder&& context);
48 /// @endcond
49
50private:
51 friend void DetachUnscopedUnsafe(Task&& task);
52};
53
54/// @brief Detaches task, allowing it to continue execution out of scope;
55/// memory safety is much better with concurrent::BackgroundTaskStorage.
56///
57/// @note After detach, Task becomes invalid.
58///
59/// @warning Variables, which are captured by reference for this task in
60/// `Async*`, should outlive the task execution. This is hard to achieve in
61/// general, detached tasks may outlive all the components!
62/// Use concurrent::BackgroundTaskStorage as a safe and efficient alternative.
64
65} // namespace engine
66
67USERVER_NAMESPACE_END