userver: userver/engine/task/task.hpp Source File
Loading...
Searching...
No Matches
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/compiler/impl/lifetime.hpp>
7#include <userver/engine/awaitable.hpp>
8#include <userver/engine/task/task_base.hpp>
9
10USERVER_NAMESPACE_BEGIN
11
12namespace engine {
13
14/// @brief Asynchronous task that has a unique ownership of the payload.
15///
16/// See engine::TaskWithResult for a type that could return a value or
17/// report an exception from the payload.
18class [[nodiscard]] Task : public TaskBase {
19public:
20 /// @brief Default constructor
21 ///
22 /// Creates an invalid task.
24
25 /// @brief If the task is still valid and is not finished, cancels it and
26 /// waits until it finishes.
27 ~Task();
28
29 /// @brief Moves the other task into this, leaving the other in an invalid
30 /// state.
31 Task(Task&& other) noexcept;
32
33 /// @brief If this Task is still valid and is not finished, cancels it and
34 /// waits until it finishes before moving the other. Otherwise just moves the
35 /// other task into this, leaving the other in invalid state.
36 Task& operator=(Task&& other) noexcept;
37
38 Task(const Task&) = delete;
39 Task& operator=(const Task&) = delete;
40
41 /// Satisfies @ref engine::Awaitable, for use with @ref engine::WaitAnyContext and friends.
42 AwaitableToken GetAwaitableToken() noexcept USERVER_IMPL_LIFETIME_BOUND;
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
67USERVER_NAMESPACE_END