Timeout for uncancellable task

I'd like to have a function that makes a DNS query using async await.
I've come across this great Apple open source project swift-async-dns-resolver that's available on iOS.

My issue is that the queries timeout is very long. For that reason, I'd like to get a function like getRecord(withTimeout: TimeInterval) async throws -> Record that throws when there is an error, or when the timeout is reached.

I have tried implementing a timeout task like here but the issue is that the current library's implementation is not cancellable, so I cancel the task, but I still have to wait for the queries timeout.

Is there any way of making the function return or throw at the end of my timeout without waiting for the other task to end?

The obvious fix here is to make the query cancellable. The underlying DNS-SD API supports cancellation.

I have code that shows how to call DNS-SD in a cancellable fashion here. It’s using DNSServiceResolve, but adapting for a different DNS-SD API would be trivial. Adapting it to be an async function that supports cancellation is a little harder, but perfectly feasible.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

1 Like