# Calling async code with task cancellation triggered by SwiftNIO channel

**URL:** <https://forums.swift.org/t/calling-async-code-with-task-cancellation-triggered-by-swiftnio-channel/70971>\
**Category:** SwiftNIO\
**Tags:** unstructured-task\
**Created:** [March 29, 2024, 2:21am UTC](https://forums.swift.org/t/calling-async-code-with-task-cancellation-triggered-by-swiftnio-channel/70971 "2024-03-29T02:21:53Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![taylorswift](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/taylorswift/32/43413_2.png) [@taylorswift](https://forums.swift.org/u/taylorswift)\
**Post date:** [March 29, 2024, 2:21am UTC](https://forums.swift.org/t/calling-async-code-with-task-cancellation-triggered-by-swiftnio-channel/70971/1 "2024-03-29T02:21:54Z")

</div>

i have some code that is relying on unstructured tasks to send the right task cancellation signals into some `async`-colored code.

```swift
try await stream.frames.executeThenClose
{
    (
        inbound:NIOAsyncChannelInboundStream<HTTP2Frame.FramePayload>,
        outbound:NIOAsyncChannelOutboundWriter<HTTP2Frame.FramePayload>
    ) in

    let request:Task<ServerResponse, any Error> = .init
    {
        try await self.respond(to: inbound)
    }
    stream.frames.channel.closeFuture.whenComplete
    {
        _ in request.cancel()
    }

    let message:ServerMessage
    do
    {
        message = .init(response: try await request.value)
    }
    catch let error
    {
        message = .init(redacting: error)
    }

    try await outbound.send(message)
}

```

but since this is relying on unstructured tasks i wondered if there was a better way to achieve this with structured concurrency.

---

<div class="post-metadata">

**Author:** ![lukasa](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lukasa/32/1232_2.png) [@lukasa](https://forums.swift.org/u/lukasa)\
**Post date:** [April 3, 2024, 4:44pm UTC](https://forums.swift.org/t/calling-async-code-with-task-cancellation-triggered-by-swiftnio-channel/70971/2 "2024-04-03T16:44:48Z")

</div>

Annoyingly we're missing some APIs here that would make this more tractable. In particular, I think we want a nice structured `cancelOnClose` API, or some way to get us to deliver you a message. Can you file a github issue for this?

---

<div class="post-metadata">

**Author:** ![adam-fowler](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/adam-fowler/32/9266_2.png) [@adam-fowler](https://forums.swift.org/u/adam-fowler)\
**Post date:** [April 8, 2024, 4:33pm UTC](https://forums.swift.org/t/calling-async-code-with-task-cancellation-triggered-by-swiftnio-channel/70971/3 "2024-04-08T16:33:11Z")

</div>

Given this was something I was just looking into the other week and hit some deadends. I added the issue [Add Channel.cancelOnClose(\_:) · Issue #2696 · apple/swift-nio · GitHub](https://github.com/apple/swift-nio/issues/2696)
