Analog of ConfigureAwait method in swift

Viewed 202

Let's imagine I have a code:

func someMethod() async {
... // processing 1
let someProperty = await someService.callSomeMethod()
... // processing 2
}

It is becoming clear from WWDC that the code executed before and after await can be executed on different threads.

But what if I want to guarantee a single thread for execution?

It is clear that if we are talking about a forced context switch to the main thread, it is enough to designate the method with @MainActor attribute, but suppose I want to isolate myself from specific threads, it is only important for me that everything in someMethod is executed in one context? (processing 1 and processing 2 have the same context)

Nutshell, there are some analog of ConfigureAwait (c sharp) in swift?

1 Answers

You can't really guarantee anything about threads, except that there is only one main thread. The async/await mechanism is totally free, whenever you await, to continue on a different thread.

But that's really low level and you shouldn't care about it. The key thing is that you can guarantee serial behavior by putting all your code into a single actor. Basically, the signal not to run a method twice concurrently is to make it a method of an actor.

(Even the very word "isolate" in your question points to an actor. That's what an actor is, it's an isolation mechanism.)

A slight complication is that actors are reentrant. This means that when an actor method says await, the actor lays itself open to being called while waiting. This can get messy. But it's not as messy as letting the actor precipitate a deadlock.

I strongly recommend that you read https://github.com/apple/swift-evolution/blob/main/proposals/0306-actors.md and https://github.com/apple/swift-evolution/blob/main/proposals/0313-actor-isolation-control.md. You might not grasp them the first time through — I sure didn't — but when I suddenly got the idea, the whole suite of concepts (actor, isolation, nonisolation, re-entrancy, Sendable) all made sense at once.

Related