简体   繁体   中英

How to start a background task with the new Swift Structured Concurrency?

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 and await expressions

Is there another Apple recommended way to start something asynchronously when it doesn't have the async flag?

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 { … }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM