# How to use withTaskCancellationHandler properly?

**URL:** <https://forums.swift.org/t/how-to-use-withtaskcancellationhandler-properly/54341>\
**Category:** Using Swift\
**Tags:** concurrency\
**Created:** [December 29, 2021, 8:29am UTC](https://forums.swift.org/t/how-to-use-withtaskcancellationhandler-properly/54341 "2021-12-29T08:29:45Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![Alejandro\_Martinez](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alejandro_martinez/32/821_2.png) [@Alejandro\_Martinez](https://forums.swift.org/u/Alejandro_Martinez)\
**Post date:** [December 29, 2021, 7:23pm UTC](https://forums.swift.org/t/how-to-use-withtaskcancellationhandler-properly/54341/5 "2021-12-29T19:23:37Z")

</div>

> [@malhal](#):
>
> Hope this example I just coded helps:

Thanks but this example is exactly what my last paragraph mentions.

> [@Alejandro\_Martinez](#):
>
> Sometimes the workaround is easy, if the object we're using can give us a cancellation token separetly from the closure that gives us the results then we can just move the assignment outside.
> 
> ```swift
> public func asyncFunc() async throws -> FeatureQueryResult {
> var request = someObject.createRequest() // gives us something that can start and also cancel the request
> return try await withTaskCancellationHandler {
> request.cancel()
> } operation: {
> try await withCheckedThrowingContinuation { continuation in
> request.start {
> continuation.resume(with: $0)
> }
> }
> }
> }
> 
> ```

So that's the easy case ^^ I still wonder about the more tricky and common one 🙂

---

_[View the full topic](https://forums.swift.org/t/how-to-use-withtaskcancellationhandler-properly/54341)._
