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/// @warning This class supports only a single concurrent awaiter. Use
17/// @ref engine::SharedTaskWithResult "SharedTaskWithResult<void>" to await the
18/// same task from multiple coroutines and report exceptions from the payload.
19///
20/// See @ref engine::TaskWithResult for a type that could return a value or
21/// report an exception from the payload.
22class [[nodiscard]] Task : public TaskBase {
23public:
24 /// @brief Default constructor
25 ///
26 /// Creates an invalid task.
28
29 /// @brief If the task is still valid and is not finished, cancels it and
30 /// waits until it finishes.
31 ~Task();
32
33 /// @brief Moves the other task into this, leaving the other in an invalid
34 /// state.
35 Task(Task&& other) noexcept;
36
37 /// @brief If this Task is still valid and is not finished, cancels it and
38 /// waits until it finishes before moving the other. Otherwise just moves the
39 /// other task into this, leaving the other in invalid state.
40 Task& operator=(Task&& other) noexcept;
41
42 Task(const Task&) = delete;
43 Task& operator=(const Task&) = delete;
44
45 /// Satisfies @ref engine::Awaitable, for use with @ref engine::WaitAnyContext and friends.
46 AwaitableToken GetAwaitableToken() noexcept USERVER_IMPL_LIFETIME_BOUND;
47
48protected:
49 /// @cond
50 // For internal use only.
51 explicit Task(impl::TaskContextHolder&& context);
52 /// @endcond
53
54private:
55 friend void DetachUnscopedUnsafe(Task&& task);
56};
57
58/// @brief Detaches task, allowing it to continue execution out of scope;
59/// memory safety is much better with concurrent::BackgroundTaskStorage.
60///
61/// @note After detach, Task becomes invalid.
62///
63/// @warning Variables, which are captured by reference for this task in
64/// `Async*`, should outlive the task execution. This is hard to achieve in
65/// general, detached tasks may outlive all the components!
66/// Use concurrent::BackgroundTaskStorage as a safe and efficient alternative.
68
69} // namespace engine
70
71USERVER_NAMESPACE_END