Search code examples
swiftconcurrencyswift-concurrency

What's the relationship between 'Task' and 'Actor' in Swift Concurrency


As we all know: Task.init creates an unstructured task that runs on the current actor, Task.detachedcreates an unstructured task that’s not part of the current actor.

I understand those differences when the context of creating a new unstructured task is on the main actor or any other actor, but what about it is on a concurrent executor other than a serial executor (which means an actor). In this situation, what's the difference between Task.init and Task.detached?

A Task does have a chance to NOT run on any actor, right?


Solution

  • Besides differing on whether to inherit actor context in tasks created with Task.init and Task.detached, there are other differences as well:

    1. Tasks created with Task.init inherit parent task's TaskLocal values.
    2. Tasks created with Task.detached don't inherit task priority. The priority should be manually provided or medium priority is used by default.

    And if the task isn't associated with any actor it is executed by concurrent executor/concurrent pool. So yes, a task might not always be associated with actor.