Running an async task with a timeout

@lyzkov
Most (if not all) of the snippets posted in this thread have some rough edges (though I am not criticizing any solution, since some things were just not available back then):

  • Using Foundation is not necessary (anymore). You can use Task.sleep(until:tolerance:clock:).
  • R should conform to Sendable. This is a requirement of TaskGroup and it warns you if you use strict concurrency.
  • If you cancel the Task in which withTimeout was started it could swallow the cancellation behavior of operation and just throw CancellationError from the Task.sleep because TaskGroup will forward the first error it receives from its children.
  • The try Task.checkCancellation() is awkward, as @ktoso already mentioned here:
1 Like