init(executorPreference:priority:operation:)
Runs the given nonthrowing operation asynchronously as part of a new top-level task on behalf of the current actor.
- iOS
- 18.0+
- macOS
- 15.0+
- tvOS
- 18.0+
- visionOS
- 2.0+
- watchOS
- 11.0+
@discardableResult init(executorPreference taskExecutor: consuming (any TaskExecutor)?, priority: TaskPriority? = nil, operation: sending @escaping () async -> Success) Parameters
- taskExecutor
the preferred task executor for this task, and any child tasks created by it. Explicitly passing
nilis interpreted as “no preference”.- priority
The priority of the task. Pass
nilto use the priority fromTask.currentPriority.- operation
The operation to perform.
This overload allows specifying a preferred TaskExecutor on which the operation, as well as all child tasks created from this task will be executing whenever possible. Refer to TaskExecutor for a detailed discussion of the effect of task executors on execution semantics of asynchronous code.
Use this function when creating asynchronous work that operates on behalf of the synchronous function that calls it. Like Task.detached(priority:operation:), this function creates a separate, top-level task. Unlike Task.detached(priority:operation:), the task created by Task.init(priority:operation:) inherits the priority and actor context of the caller, so the operation is treated more like an asynchronous extension to the synchronous operation.
You need to keep a reference to the task if you want to cancel it by calling the Task.cancel() method. Discarding your reference to a detached task doesn’t implicitly cancel that task, it only makes it impossible for you to explicitly cancel the task.