I'm writing a test in Swift. The function that I'm testing blocks the current thread so I want to run it on the background. Previously I would wrap it in DispatchQueue.global.async {}
.
With Swift's new structured concurrency, I found Task.detached
. However, the notes on it say
Creating detached tasks should, generally, be avoided in favor of using
async
functions,async let
declarations andawait
expressions
Is there another Apple recommended way to start something asynchronously when it doesn't have the async
flag?
CodePudding user response:
The documentation is just telling you that in many cases, structured concurrency should be preferred, but where you need unstructured concurrency, feel free to use it.
That having been said, rather than creating a detached task, you can just start an unstructured task. See The Swift Programming Language: Concurrency: Unstructured Tasks. In short, rather than creating a detached task with Task.detached { … }
, you can just use Task { … }