Hello everyone ,
I have a little problem with @MainActor
, and I don't know if it's a swift bug or a misunderstanding on my part?
If we consider the following code:
actor Bar {
enum BarError: Error {
case unknownError
}
func longAsyncWork() async throws {
print("longAsyncWork thread : \(Thread.current.description)")
try await Task.sleep(nanoseconds: 1000000000)
throw BarError.unknownError
}
}
​
​
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.simpleFunction()
self.launchTask()
}
func simpleFunction() {
print("simpleFunction thread : \(Thread.current.description)")
}
func launchTask() {
print("launch Task thread : \(Thread.current.description)")
Task {
await self.task()
}
}
func task() async {
do {
print("In Do Task thread : \(Thread.current.description)")
try await Bar().longAsyncWork()
} catch {
print("In catch Task thread : \(Thread.current.description)")
self.update()
}
}
@MainActor
func update() {
print("update thread : \(Thread.current.description)")
}
}
And this output :
simpleFunction thread : <_NSMainThread: 0x6000027146c0>{number = 1, name = main}
launch Task thread : <_NSMainThread: 0x6000027146c0>{number = 1, name = main}
In Do Task thread : <NSThread: 0x6000027249c0>{number = 3, name = (null)}
longAsyncWork thread : <NSThread: 0x6000027249c0>{number = 3, name = (null)}
In catch Task thread : <NSThread: 0x600002748300>{number = 6, name = (null)}
update thread : <NSThread: 0x600002748300>{number = 6, name = (null)}
For me the update function should always be executed on the MainThread ?
Misunderstanding on my part? @MainActor issue? Something else ?
And if I misunderstand something what is the good fix ?
(Knowing that the @MainActor annotation is superficial because ViewController is already in theory @MainActor )