# \[Pitch\] Task Cancellation Shields

**URL:** <https://forums.swift.org/t/pitch-task-cancellation-shields/83379>\
**Category:** Pitches\
**Tags:** concurrency\
**Created:** [November 23, 2025, 11:51am UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379 "2025-11-23T11:51:30Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [November 23, 2025, 11:51am UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/1 "2025-11-23T11:51:30Z")

</div>

Good day everyone,

Making use of the week where development branches are locked, I’d like to pre-flight a pitch which is a follow-up to the async deinit we’ve done recently as part of [SE-0493: Support `async` calls in `defer` bodies](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0493-defer-async.md): task cancellation shields.

In that proposal’s review there was a discussion about “shielding” pieces of code from observing the effects of task cancellation. This proposal offers an API to do that.

Task cancellation shields allow a piece of code to run while ignoring the effects of cancellation. It does not prevent a task from being cancelled, however it does prevent the task from “observing” the cancellation (either by using isCancelled or cancellation handlers).

Please refer to the full proposal text over here: **[SE-NNNN: Task Cancellation Shields](https://github.com/ktoso/swift-evolution/blob/patch-13/proposals/NNNN-task-cancellation-shields.md)**

Please submit any typos or editorial fixes to the proposal [pull request](https://github.com/swiftlang/swift-evolution/pull/3037/files) and let’s keep this thread focused on functionality and semantics.

Thanks!

---

<div class="post-metadata">

**Author:** ![johannesweiss](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/johannesweiss/32/38183_2.png) [@johannesweiss](https://forums.swift.org/u/johannesweiss)\
**Post date:** [November 23, 2025, 1:34pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/2 "2025-11-23T13:34:44Z")

</div>

+1, this is one of the core requirements to build Structured Concurrency code. Today we rely on the `Task.value { try await cleanup }.value` which is bad for the reason stated the proposal.

@ktoso just to double-check. The task hierarchy inside of a cancellation shield can also be cancelled, right?

A very common pattern is

```swift
defer {
   // might be cancelled from surrounding tasks
   try await withTaskCancellationShield {
      // deffo NOT cancelled when we get here
      try await withTimeout(.seconds(10)) {
           // might be cancelled (e.g. if the timeout fires)
           try await decommissionResource() // often uses HTTP or other stuff that can time out
      }
   }
}

```

---

<div class="post-metadata">

**Author:** ![Jnosh](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jnosh/32/37375_2.png) [@Jnosh](https://forums.swift.org/u/Jnosh)\
**Post date:** [November 23, 2025, 2:05pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/3 "2025-11-23T14:05:32Z")

</div>

Strong +1.

As mentioned in the proposal, this is both very important so that async code that might react to cancellation can be used for cleanup and the runtime can implement this more cleanly and efficiently than manual workarounds.

I am also very glad that the proposal includes a way to test if a cancellation shield is currently active and to test for cancellation ignoring a cancellation shield.

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [November 24, 2025, 12:15pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/4 "2025-11-24T12:15:51Z")

</div>

You’d have to show the implementation of with timeout to answer that, if it has a child task to run that block if code then yes, if no, then as-proposed that cannot observe cancelation because “the current task is shielded”.

Since this is an imaginary with timeout, I’d rather spell out what you actually mean there.

---

<div class="post-metadata">

**Author:** ![FranzBusch](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/franzbusch/32/19447_2.png) [@FranzBusch](https://forums.swift.org/u/FranzBusch)\
**Post date:** [November 24, 2025, 1:48pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/5 "2025-11-24T13:48:13Z")

</div>

+1 on the proposal. As @johannesweiss mentioned this is necessary to write structured concurrency code when managing resources. As it stands today, using an unstructured task for blocking the cancellation of a clean-up is the only workaround and it comes with a lot of downsides.

---

<div class="post-metadata">

**Author:** ![jamieQ](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jamieq/32/5117_2.png) [@jamieQ](https://forums.swift.org/u/jamieQ)\
**Post date:** [November 24, 2025, 2:02pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/6 "2025-11-24T14:02:28Z")

</div>

> [@ktoso](#):
>
> I’d like to pre-flight a pitch which is a follow-up to the async deinit we’ve done recently

just to clarify – is this meant to read '...is a follow-up to the async _defer_...', or is there something about async deinit that was involved in the async defer proposal or its implementation that is relevant here?

---

<div class="post-metadata">

**Author:** ![johannesweiss](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/johannesweiss/32/38183_2.png) [@johannesweiss](https://forums.swift.org/u/johannesweiss)\
**Post date:** [November 24, 2025, 7:16pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/7 "2025-11-24T19:16:55Z")

</div>

> [@ktoso](#):
>
> You’d have to show the implementation of with timeout to answer that, if it has a child task to run that block if code then yes

It would have a child task that it cancels when the timeout has been reached. Is there another way you could implement withTimeout?

---

<div class="post-metadata">

**Author:** ![EthanLS](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ethanls/32/34412_2.png) [@EthanLS](https://forums.swift.org/u/EthanLS)\
**Post date:** [November 24, 2025, 7:44pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/8 "2025-11-24T19:44:40Z")

</div>

First thing I looked for was whether we could check for the shield, which you added two clean APIs for! 🙂 They seemed ideal.

My only concern is its yet another piece of cognitive overhead for Tasks, but frankly, I don't have any better proposals, and the current lack of this functionality adds its own equal-or-worse overhead to reason through and work around.

---

<div class="post-metadata">

**Author:** ![tourultimate](https://avatars.discourse-cdn.com/v4/letter/t/85f322/32.png) [@tourultimate](https://forums.swift.org/u/tourultimate)\
**Post date:** [November 24, 2025, 10:28pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/9 "2025-11-24T22:28:45Z")

</div>

Should this be

`guard !Task.isCancelled else {`

In this code from the proposal:

```swift
extension SomeSystem { 
  func performAction(_ action: some SomeAction) { 
    guard Task.isCancelled else {
      // oh no! 
      // If Resource.cleanup calls this while being in a cancelled task,
      // the action would never be performed!
      return 
    }
    // ... 
  }
}

```

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [November 25, 2025, 1:39am UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/10 "2025-11-25T01:39:42Z")

</div>

> [@johannesweiss](#):
>
> It would have a child task that it cancels when the timeout has been reached.

Thanks for spelling this out, I think it’s important to be very specific when we discuss semantics here.

Yeah, child tasks are able to be cancelled independently. It’s kinda implied in the proposal but I’ll add an explicit example of this.

> [@johannesweiss](#):
>
> Is there another way you could implement withTimeout?

If it were implemented by the runtime we could imagine other ways; so I want to be very clear which one you were asking about, just to make sure we’re discussing a child task there.

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [November 25, 2025, 1:40am UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/11 "2025-11-25T01:40:46Z")

</div>

Yes, you can submit a fix to the PR or I’ll get to it at some point – thank you

---

<div class="post-metadata">

**Author:** ![grynspan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/grynspan/32/15315_2.png) [@grynspan](https://forums.swift.org/u/grynspan)\
**Post date:** [November 25, 2025, 2:36am UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/12 "2025-11-25T02:36:35Z")

</div>

Can this concept be generalized to other task state such as task locals? (_Should_ it be generalized?)

---

<div class="post-metadata">

**Author:** ![John\_McCall](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/john_mccall/32/1351_2.png) [@John\_McCall](https://forums.swift.org/u/John_McCall)\
**Post date:** [November 25, 2025, 3:54am UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/13 "2025-11-25T03:54:43Z")

</div>

Cancellation is something that generally comes from outside the task, which is why the task may usefully want to shield some of its operations from it. Priority escalation is in the same bucket, except I can’t think of any reason a task would want to except itself from that. All of the other task state is something the task itself asks for; if the task wants a task local to be different within a scope, it should just change it normally.

---

<div class="post-metadata">

**Author:** ![jamieQ](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jamieq/32/5117_2.png) [@jamieQ](https://forums.swift.org/u/jamieQ)\
**Post date:** [November 25, 2025, 11:35am UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/15 "2025-11-25T11:35:30Z")

</div>

what's supposed to happen in a case like this:

```swift
await withTaskCancellationShield {
  do {
    async let _ = {
      var count = 0
      while true {
        count += 1; print("count: ", count)
        if Task.isCancelled { break }
        try? await Task.sleep(for: .seconds(1))
      }
    }()
  } // implicit child task cancelled here... is it observable?
}

```

* * *

edit: and another case that i think isn't directly mentioned in the current proposal text – what's the impact on `Task.checkCancellation()`? i would assume it just becomes a noop if under an active 'shield'?

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [November 26, 2025, 1:40pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/16 "2025-11-26T13:40:27Z")

</div>

> [@jamieQ](#):
>
> what's supposed to happen in a case like this:
> 
> ```swift
> await withTaskCancellationShield {
> async let _ = { ... }
> }
> 
> ```

This is an “explicit cancellation” for what it’s worth, so yes this task is cancelled and would not hang.

Shields prevent cancellation from “passing through” the shield if you will, so if the outside task was cancelled, the inner child task would not be. This however is the inner task being explicitly cancelled; this isn’t the same as cancellation propagating from paren task to child task.

It’s a good example worth adding to the proposal so that people can be clear about the intended behavior, thanks for adding this to the discussion.

---

<div class="post-metadata">

**Author:** ![ktoso](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ktoso/32/44526_2.png) [@ktoso](https://forums.swift.org/u/ktoso)\
**Post date:** [November 26, 2025, 1:41pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/17 "2025-11-26T13:41:13Z")

</div>

> [@jamieQ](#):
>
> what's the impact on `Task.checkCancellation()`?

in any place in the proposal effects described to `isCancelled` are the same to `checkCancellation` because all check does is “isCancelled → throw”.

I’ll add a paragraph to be clearer about this.

---

<div class="post-metadata">

**Author:** ![jamieQ](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jamieq/32/5117_2.png) [@jamieQ](https://forums.swift.org/u/jamieQ)\
**Post date:** [November 26, 2025, 2:08pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/18 "2025-11-26T14:08:54Z")

</div>

> [@ktoso](#):
>
> This is an “explicit cancellation” for what it’s worth, so yes this task is cancelled and would not hang.

perhaps things have changed since it was written, but the description of this scenario as outlined in the async let evolution proposal [is characterized](https://github.com/swiftlang/swift-evolution/blob/d2111b0f8e725ffa68d124e9570cccb20bde194c/proposals/0317-async-let.md#implicit-async-let-awaiting) as an 'implicit' cancel (and i guess that's how i've always thought of the behavior).

> [@ktoso](#):
>
> Shields prevent cancellation from “passing through” the shield if you will, so if the outside task was cancelled, the inner child task would not be. This however is the inner task being explicitly cancelled; this isn’t the same as cancellation propagating from paren task to child task.

thanks, this was a very helpful clarification. IIUC then, this feature is purely about influencing automatic _propagation_ of the cancelled state through the Task tree. i suppose my mental model of structured concurrency has been that the cancelled state for the entire tree is the same, so there's a singular 'true' value, and this feature would simply hide that value from certain subtrees in the graph. clearly that model isn't quite right due to how task groups can be independently cancelled. so perhaps a more accurate model is that each 'node' of the tree has an independent cancelled bit, and the default behavior just propagates the value from ancestors to children in a 'natural' way. this feature gives a means of 'opting out' of that propagation (apologies if this is obvious to everyone else, mostly writing it out for myself...).

so... at the risk of being redundant, going back to an async let example; if we had code like this:

```swift
let task = Task {
  await withTaskCancellationShield {
    async let whatever = {
      await withTaskCancellationHandler { /* wait for a while */ } onCancel: { ... }
    }()
    await whatever
  }
}
task.cancel()

```

the async let child will _not_ observe the parent task cancellation (it's not propagated due to the shield), but if we didn't explicitly await it, it would observe its _own_ cancellation due to exiting scope without being awaited. is that right?

* * *

edit: actually, maybe i still don't quite get it. the proposal currently says:

> They do not prevent a task from being cancelled, however, they affect the observation of the cancelled status while executing in a "shielded" piece of code.

in the case of child tasks... is it true that a child is still 'really cancelled' if the parent has been but the child was formed under a 'shield'? i guess i feel i'm floundering a bit with how to properly think about what 'isCancelled' actually means now if it's not 'this region of the Task tree is in the cancelled state'.

---

<div class="post-metadata">

**Author:** ![Avi](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/avi/32/2962_2.png) [@Avi](https://forums.swift.org/u/Avi)\
**Post date:** [November 26, 2025, 5:19pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/19 "2025-11-26T17:19:52Z")

</div>

Would it not be the case that `async let` being implicitly cancelled at the end of scope mean that there’s no code that could be observing the cancellation? Can implicit cancellation _ever_ be observed?

---

<div class="post-metadata">

**Author:** ![John\_McCall](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/john_mccall/32/1351_2.png) [@John\_McCall](https://forums.swift.org/u/John_McCall)\
**Post date:** [November 26, 2025, 5:38pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/20 "2025-11-26T17:38:10Z")

</div>

You’re chicken-and-egging, I think. The `async let` task can observe that it’s been cancelled, starting when the parent task _begins_ to leave the scope of the `async let`. The parent task can’t _finish_ leaving the scope until the `async let` task completes, but that doesn’t mean the task has to have completed _already_.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [November 26, 2025, 11:54pm UTC](https://forums.swift.org/t/pitch-task-cancellation-shields/83379/21 "2025-11-26T23:54:40Z")

</div>

> [@ktoso](#):
>
> Shields prevent cancellation from “passing through” the shield if you will, so if the outside task was cancelled, the inner child task would not be. This however is the inner task being explicitly cancelled; this isn’t the same as cancellation propagating from paren task to child task.

Would this be made more clear with another name for the API, such as `withoutPropagatingTaskCancellation`? It seems like there's a lot of struggle with this notion of what a "shield" does, which doesn't seem to need its own term of art here.

[Next page](https://forums.swift.org/t/pitch-task-cancellation-shields/83379.md?page=2)
