# Equivalent to withTaskCancellationShield to use in previous OS versions

**URL:** <https://forums.swift.org/t/equivalent-to-withtaskcancellationshield-to-use-in-previous-os-versions/89612>\
**Category:** Using Swift\
**Tags:** concurrency\
**Created:** [September 17, 2026, 8:03am UTC](https://forums.swift.org/t/equivalent-to-withtaskcancellationshield-to-use-in-previous-os-versions/89612 "2026-09-17T08:03:11Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![EngOmarElsayed](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/engomarelsayed/32/45556_2.png) [@EngOmarElsayed](https://forums.swift.org/u/EngOmarElsayed)\
**Post date:** [September 17, 2026, 8:03am UTC](https://forums.swift.org/t/equivalent-to-withtaskcancellationshield-to-use-in-previous-os-versions/89612/1 "2026-09-17T08:03:12Z")

</div>

For some reason, I found out that `withTaskCancellationShield ` is only available in 27 OS which is interesting and annoying at the same time.

```swift
func processFile(at url: URL) async throws {
    let handle = try FileHandle(forReadingFrom: url)

    defer {
        // flushMetrics is a network call, so it can suspend after cancellation
        // is requested; the shield ensures it runs to completion and isn't
        // included in cancellation.
        await withTaskCancellationShield {
            await flushMetrics(for: url)
            try? handle.close()
        }
    }

    try await processContents(of: handle)
}

```

So I was asking myself what if I use `Task.detached` to have the same behaviour but pre 27 OS, something like this:

```swift
func processFile(at url: URL) async throws {
    let handle = try FileHandle(forReadingFrom: url)

    defer {
        Task.detached {
            await flushMetrics(for: url)
            try? handle.close()
        }
    }

    try await processContents(of: handle)
}

```

Since `Task.detached ` detaches the task from the parent task, so if the parent task is canceled this task shouldn't be affected.

if this solution is wrong, is there any other way to have something similar to `withTaskCancellationShield ` to use in previous os versions ?

---

<div class="post-metadata">

**Author:** ![Jon\_Shier](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jon_shier/32/921_2.png) [@Jon\_Shier](https://forums.swift.org/u/Jon_Shier)\
**Post date:** [September 17, 2026, 2:58pm UTC](https://forums.swift.org/t/equivalent-to-withtaskcancellationshield-to-use-in-previous-os-versions/89612/2 "2026-09-17T14:58:48Z")

</div>

You don't need to use `Task.detached` for this (and should generally avoid `Task.detached` anyway), all `Task`s break automatic cancellation since they're technically unstructured.

FYI, when new Swift functionality is OS limited like this, it's typically because they use a new type or Swift runtime capability that can't be back deployed on Apple platforms.

---

<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:** [September 19, 2026, 3:23am UTC](https://forums.swift.org/t/equivalent-to-withtaskcancellationshield-to-use-in-previous-os-versions/89612/3 "2026-09-19T03:23:40Z")

</div>

Yeah we're not able to back deploy this easily because it is a new runtime feature;

Your snippet is almost close enough... The problem you have though is that you don't await on the flushing/closing which could be a problem, so I would recommend putting an `await Task{}.value` there inside the `defer` (which supports async since [swift-evolution/proposals/0493-defer-async.md at main · swiftlang/swift-evolution · GitHub](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0493-defer-async.md))

```swift

    defer {
        await Task {
            await flushMetrics(for: url)
            try? handle.close()
        }.value
    }

```

---

<div class="post-metadata">

**Author:** ![EngOmarElsayed](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/engomarelsayed/32/45556_2.png) [@EngOmarElsayed](https://forums.swift.org/u/EngOmarElsayed)\
**Post date:** [September 20, 2026, 8:56am UTC](https://forums.swift.org/t/equivalent-to-withtaskcancellationshield-to-use-in-previous-os-versions/89612/4 "2026-09-20T08:56:58Z")

</div>

but why awaiting on the `Task{}.value` is better and what is the problems that can happen if otherwise was happened ?

---

<div class="post-metadata">

**Author:** ![EngOmarElsayed](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/engomarelsayed/32/45556_2.png) [@EngOmarElsayed](https://forums.swift.org/u/EngOmarElsayed)\
**Post date:** [September 20, 2026, 8:58am UTC](https://forums.swift.org/t/equivalent-to-withtaskcancellationshield-to-use-in-previous-os-versions/89612/5 "2026-09-20T08:58:32Z")

</div>

> [@Jon\_Shier](#):
>
> FYI, when new Swift functionality is OS limited like this, it's typically because they use a new type or Swift runtime capability that can't be back deployed on Apple platforms.

I suspected that this is the reason but wanted to make sure. Either way, thanks for all the swift team for there continues effort on making this language better every day

---

<div class="post-metadata">

**Author:** ![Joannis\_Orlandos](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joannis_orlandos/32/732_2.png) [@Joannis\_Orlandos](https://forums.swift.org/u/Joannis_Orlandos)\
**Post date:** [September 20, 2026, 10:17pm UTC](https://forums.swift.org/t/equivalent-to-withtaskcancellationshield-to-use-in-previous-os-versions/89612/6 "2026-09-20T22:17:27Z")

</div>

Detached had the additional effect that it erases the task local values. It can lead to some unexpected side effects of that is not explicitly what you are looking for

---

<div class="post-metadata">

**Author:** ![michelf](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/michelf/32/1180_2.png) [@michelf](https://forums.swift.org/u/michelf)\
**Post date:** [September 21, 2026, 12:17am UTC](https://forums.swift.org/t/equivalent-to-withtaskcancellationshield-to-use-in-previous-os-versions/89612/7 "2026-09-21T00:17:09Z")

</div>

> [@EngOmarElsayed](#):
>
> but why awaiting on the `Task{}.value` is better and what is the problems that can happen if otherwise was happened ?

It does the same thing as `withTaskCancellationShield` does so if you want it to be a drop-in replacement you have to do this. Otherwise you have to think about whether it matters if what you're doing in the closure should be happening concurrently with the rest of the parent task.

For instance, with this:

```swift
func processFile(at url: URL) async throws {
    let handle = try FileHandle(forReadingFrom: url)

    defer {
        Task {
            await flushMetrics(for: url)
            try? handle.close()
        }
        // not awaitting for the task to be finished
    }

    try await processContents(of: handle)
}

```

If in `processFile` you don't wait for the handle to close before returning, calling `processFile` many times in a loop could end up exhausting the number of file handles the system allocates to your process if the created cleanup tasks cannot keep up for some reason (most likely other threads/tasks keeping the CPU busy). If you wait for the file to close you'll have no such issue because you know the file handle is closed before you can call `processFile` again.

Another effect is there will be no guaranty about the order `flushMetrics` will be called since multiple cleanup tasks will be scheduled to run in parallel in the background. Perhaps it does not matter in this specific case, but that depends entirely on what you're doing in that function. And since the order in which those cleanup tasks will run is not deterministic it will introduce some randomness to any bug you might have in there.

So unless there's a compelling reason to cleanup things concurrently, I'd refrain from doing it. Running things in the same order every time will keep your resource usage, your logs, and your debugging sessions more deterministic.

---

<div class="post-metadata">

**Author:** ![EngOmarElsayed](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/engomarelsayed/32/45556_2.png) [@EngOmarElsayed](https://forums.swift.org/u/EngOmarElsayed)\
**Post date:** [September 21, 2026, 9:08am UTC](https://forums.swift.org/t/equivalent-to-withtaskcancellationshield-to-use-in-previous-os-versions/89612/8 "2026-09-21T09:08:35Z")

</div>

Thanks for this detailed explanation ❤

---

<div class="post-metadata">

**Author:** ![EngOmarElsayed](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/engomarelsayed/32/45556_2.png) [@EngOmarElsayed](https://forums.swift.org/u/EngOmarElsayed)\
**Post date:** [September 26, 2026, 9:26am UTC](https://forums.swift.org/t/equivalent-to-withtaskcancellationshield-to-use-in-previous-os-versions/89612/9 "2026-09-26T09:26:53Z")

</div>

```swift
public nonisolated(nonsending) func withTaskCancellationShield<Value: Sendable, Failure>(
  _ operation: sending @escaping () async throws(Failure) -> Value
) async throws(Failure) -> Value {
  if #available(anyAppleOS 27, *) {
    return await withTaskCancellationShieldBack { await operation() }
  } else {
    let result: Result<Value, Failure> = await Task {
      do throws(Failure) {
        return .success(try await operation())
      } catch {
        return .failure(error)
      }
    }.value

    return try result.get()
  }
}

```

is this wrapper right ? or am I missing something ? @michelf

---

<div class="post-metadata">

**Author:** ![michelf](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/michelf/32/1180_2.png) [@michelf](https://forums.swift.org/u/michelf)\
**Post date:** [September 26, 2026, 1:58pm UTC](https://forums.swift.org/t/equivalent-to-withtaskcancellationshield-to-use-in-previous-os-versions/89612/10 "2026-09-26T13:58:29Z")

</div>

Looks good at a glance.
