@@ -55,6 +55,39 @@ public func withGracefulShutdownHandler<T>(
55
55
return try await operation ( )
56
56
}
57
57
58
+ /// Execute an operation with a graceful shutdown or task cancellation handler that’s immediately invoked if the current task is
59
+ /// shutting down gracefully or has been cancelled.
60
+ ///
61
+ /// This doesn’t check for graceful shutdown, and always executes the passed operation.
62
+ /// The operation executes on the calling execution context and does not suspend by itself, unless the code contained within the closure does.
63
+ /// If graceful shutdown or task cancellation occurs while the operation is running, the cancellation/graceful shutdown handler will execute
64
+ /// concurrently with the operation.
65
+ ///
66
+ /// When `withTaskCancellationOrGracefulShutdownHandler` is used in a Task that has already been gracefully shutdown or cancelled, the
67
+ /// `onCancelOrGracefulShutdown` handler will be executed immediately before operation gets to execute. This allows the `onCancelOrGracefulShutdown`
68
+ /// handler to set some external “shutdown” flag that the operation may be atomically checking for in order to avoid performing any actual work
69
+ /// once the operation gets to run.
70
+ ///
71
+ /// - Important: This method will only set up a graceful shutdown handler if run inside ``ServiceGroup`` otherwise no graceful shutdown handler
72
+ /// will be set up.
73
+ ///
74
+ /// - Parameters:
75
+ /// - operation: The actual operation.
76
+ /// - handler: The handler which is invoked once graceful shutdown or task cancellation has been triggered.
77
+ // Unsafely inheriting the executor is safe to do here since we are not calling any other async method
78
+ // except the operation. This makes sure no other executor hops would occur here.
79
+ @_unsafeInheritExecutor
80
+ public func withTaskCancellationOrGracefulShutdownHandler< T> (
81
+ operation: ( ) async throws -> T ,
82
+ onCancelOrGracefulShutdown handler: @Sendable @escaping ( ) -> Void
83
+ ) async rethrows -> T {
84
+ return try await withTaskCancellationHandler {
85
+ try await withGracefulShutdownHandler ( operation: operation, onGracefulShutdown: handler)
86
+ } onCancel: {
87
+ handler ( )
88
+ }
89
+ }
90
+
58
91
/// Waits until graceful shutdown is triggered.
59
92
///
60
93
/// This method suspends the caller until graceful shutdown is triggered. If the calling task is cancelled before
0 commit comments