Skip to content

Commit 1e7e518

Browse files
committed
Document more explicitly closure lifetime of a Task init
1 parent b1abe1b commit 1e7e518

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

stdlib/public/Concurrency/Task.swift

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,43 @@ import Swift
7676
/// like the reason for cancellation.
7777
/// This reflects the fact that a task can be canceled for many reasons,
7878
/// 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+
/// ```
79116
@available(SwiftStdlib 5.1, *)
80117
@frozen
81118
public struct Task<Success: Sendable, Failure: Error>: Sendable {

0 commit comments

Comments
 (0)