@@ -55,6 +55,18 @@ public func withGracefulShutdownHandler<T>(
55
55
return try await operation ( )
56
56
}
57
57
58
+ /// Suspend the current task until graceful shutdown is executed.
59
+ ///
60
+ /// A common use-case is to call this method in the `operation` closure of ``withGracefulShutdownHandler(operation:onGracefulShutdown:)``
61
+ /// when you are only interested in executing a closure upon graceful shutdown, and nothing else.
62
+ public func waitForGracefulShutdown( ) async {
63
+ guard let gracefulShutdownManager = TaskLocals . gracefulShutdownManager else {
64
+ return
65
+ }
66
+
67
+ await gracefulShutdownManager. waitForGracefulShutdown ( )
68
+ }
69
+
58
70
/// This is just a helper type for the result of our task group.
59
71
enum ValueOrGracefulShutdown < T: Sendable > : Sendable {
60
72
case value( T )
@@ -138,6 +150,8 @@ public final class GracefulShutdownManager: @unchecked Sendable {
138
150
fileprivate var handlerCounter : UInt64 = 0
139
151
/// A boolean indicating if we have been shutdown already.
140
152
fileprivate var isShuttingDown = false
153
+ /// Continuations to resume after all of the handlers have been executed.
154
+ fileprivate var gracefulShutdownFinishedContinuations = [ CheckedContinuation < Void , Never > ] ( )
141
155
}
142
156
143
157
private let state = LockedValueBox ( State ( ) )
@@ -191,6 +205,25 @@ public final class GracefulShutdownManager: @unchecked Sendable {
191
205
}
192
206
193
207
state. handlers. removeAll ( )
208
+
209
+ for continuation in state. gracefulShutdownFinishedContinuations {
210
+ continuation. resume ( )
211
+ }
212
+
213
+ state. gracefulShutdownFinishedContinuations. removeAll ( )
214
+ }
215
+ }
216
+
217
+ func waitForGracefulShutdown( ) async {
218
+ await withCheckedContinuation { continuation in
219
+ self . state. withLockedValue { state in
220
+ guard !state. isShuttingDown else {
221
+ continuation. resume ( )
222
+ return
223
+ }
224
+
225
+ state. gracefulShutdownFinishedContinuations. append ( continuation)
226
+ }
194
227
}
195
228
}
196
229
}
0 commit comments