Is Task.detached still useful?

Yes, setting the task executor preference works to avoid inheriting the current isolation.

This is accomplished by the Task initializer not using @_inheritActorContext for the variants setting a task executor preference.

I think it's OK as far as signaling intentions go although not ideal since it's using a side effect of starting a task with a task executor preference and it prevents inheriting a custom task executor preference.

Another frequently used approach is starting the task from a nonisolated wrapper. That avoids having to set a task executor preference but needs some extra boilerplate.

@MainActor
func f() {
    startTask()
}

// assuming nonisolated default actor isolation
// the function would need to be nonisolated explicitly when using MainActor default actor isolation
func startTask() {
    Task {
        // not isolated to MainActor
    }
}

The "ideal" solution is part of the Closure Isolation pitch which allows you to explicitly avoid inheriting isolation.

// Today, you can already override the isolation explicitly:
Task { @MainActor in
    // starts on the MainActor, no matter the isolation we started the task from
}

// With the closure isolation pitch you could also specify nonisolated to make the closure explicitly nonisolated:
Task { nonisolated in
    // starts nonisolated on the task executor, no matter the isolation we started the task from
}

If you want to try it, you can enable the ClosureIsolation experimental feature, the nonisolated in part of the pitch is already implemented.

Personally I share your preference for not using Task.detached for this purpose. While it works, not inheriting all the other context like task locals should be an explicit choice. Using Task.detached just to avoid inheriting the current isolation is liable to bite you in the future.

On Apple platforms specifically, there is at least one more item that detached tasks don't inherit that I am aware of, the current activity. I would assume that detached tasks probably match detached DispatchWorkItems in general in this regard but I don't know if there are any context attributes beyond priority and activity.

2 Likes