Skip to content

Actor Isolation

Compare
Choose a tag to compare
@swhitty swhitty released this 11 Mar 06:21
· 2 commits to main since this release
de0b23e

Adds explicit actor isolation to ensure the closure is executed within the actors isolation:

let val: String = await withIdentifiableContinuation(isolation: self) { 
    $0.resume(returning: "bar")
}

This allows actors to synchronously start continuations and mutate their isolated state before suspension occurs. The onCancel: handler is @Sendable and can be called at any time after the body has completed. Manually check Task.isCancelled before creating the continuation to prevent performing unrequired work.

let val: String = await withIdentifiableContinuation(isolation: self) {
  // executed within actor isolation so can immediatley mutate actor state
  continuations[$0.id] = $0
} onCancel: { id in
  // @Sendable closure executed outside of actor isolation requires `await` to mutate actor state
  Task { await self.cancelContinuation(with: id) }
}

Previous versions used async closures and unstructured tasks to work with actors but SE-0420 Inheritance of Actor isolation includes the new #isolation keyword that will allow isolation: self to be automatically filled in by the compiler.