Detached Task
date
Apr 26, 2024
slug
task-detach
status
Published
tags
concurrency
multithreading
summary
A note about what a detached task is and where it can be used.
type
Post
A separate task performs the operation asynchronously within a new top-level task.
Such a task does not inherit the context and priorities of its parent task. It will also not delay the completion of other tasks, thereby you lose control over the sequence of execution.
This goes against the structured concurrency principle of Swift Concurrency, but in some cases, using
Task.detached
can be considered reasonable. For example, if you need to perform an independent operation like:- uploading non-sensitive data (logs or analytics) to the server, which should not affect the user interface / does not have loading indicators, etc.;
- cleaning local storage.
Together with the properties mentioned above,
Task.detached
does not have automatic cancellation when the parent task is canceled.