Task not suspending while waiting for continuation?

Hey there,

I am using Swift Concurrency to handle networking with my devices. For certain reasons, I have to manually keep track of pending requests until a response comes in. I am doing so using continuations.

However, I am not sure if this is even remotely okay. Specifically, upon using Instruments, I realized that a lot of continuations were created (which is expected). However, unless I am misinterpreting Instruments here, it seems like the Tasks in which the continuation is awaited does not suspend:

Ran continuation for 10.02s that ended with...

This is the code I believe to be the culprit here; Is it possible that this Task is not suspending while waiting for the continuation to resume? Am I missing something here?

    /// Writes the command to the socket and awaits its response.
    private func write(command: DeviceCommand, with timeout: UInt64) async throws -> DeviceCommand {
        let commandData = try parser.print(command)

        async let response: DeviceCommand = try withCheckedThrowingContinuation { continuation in
            Task {
                let uniqueRequestId: UUID
                do {
                    uniqueRequestId = await commandHandler.registerPendingCommand(for: command.id, timeout: timeout, on: continuation)
                    try await socket.send(.data(commandData))
                } catch {
                    // deregister to prevent timeout from firing continuation twice
                    await commandHandler.deregisterPendingCommand(for: command.id, with: uniqueRequestId)
                    continuation.resume(throwing: error)
                }
            }
        }

        return try await response
    }

It depends what all those async calls are doing.

async doesn't mean "definitely suspends" but just that it might. If e.g. the socket.send is actually blocking on anything that may end up with the task not suspending -- it only can suspend if the underlying functions actually "await".

Also, how do you measure the "ran continuation for..."? Just wall clock time isn't going to tell you anything about if a task was suspended or not after all.

1 Like

@ktoso Well the write is not the issue I believe.

Let me give some more context:
The PendingCommandHandler enqueues all outgoing commands (by storing the continuation). Once a response for that command is received, that continuation is resumed.

I did not measure this myself; I used Xcodes Instruments with the Swift Concurrency Profiling template to inspect my app. That‘s where the „Continuation ran for…“ came from.

Maybe it‘s just the wording of Instruments and nothing is actually wrong with this code; but I want to ensure that this task is not alive and running for e.g. 10 seconds while waiting for the continuation.