@@ -76,6 +76,43 @@ import Swift
76
76
/// like the reason for cancellation.
77
77
/// This reflects the fact that a task can be canceled for many reasons,
78
78
/// and additional reasons can accrue during the cancellation process.
79
+ ///
80
+ /// ### Task closure lifetime
81
+ /// Tasks initialized with a closure, representing the code that will be executed by this task.
82
+ ///
83
+ /// Once this code has ran to completion, and the task therefore has completed, resulting in either
84
+ /// a failure or result value, this closure is eagerly released.
85
+ ///
86
+ /// Keeping the `Task` object retained, will not indefinitely keep the closure retained.
87
+ /// This means that tasks rarely need to capture values as `weak`, since when they complete
88
+ /// any references they hold are released (as the closure is released).
89
+ ///
90
+ /// For example, in this example, it is not necessary to capture the actor as weak,
91
+ /// because as the task completes it'll let go of the actor reference, breaking the
92
+ /// reference cycle between the Task and the actor holding it.
93
+ ///
94
+ /// ```
95
+ /// struct Work: Sendable {}
96
+ ///
97
+ /// actor Worker {
98
+ /// var work: Task<Work, Never>?
99
+ ///
100
+ /// deinit {
101
+ ///
102
+ /// print("deinit")
103
+ /// }
104
+ ///
105
+ /// func start() {
106
+ /// work = Task {
107
+ /// return Work()
108
+ /// }
109
+ /// }
110
+ /// }
111
+ ///
112
+ /// await Actor().start()
113
+ /// // no references to Actor other than inside the Task
114
+ /// // as the Task completes; the closure is destroyed releasing the actor.
115
+ /// ```
79
116
@available ( SwiftStdlib 5 . 1 , * )
80
117
@frozen
81
118
public struct Task < Success: Sendable , Failure: Error > : Sendable {
0 commit comments