Equivalence of Task and MainActor.assumeIsolated

It appears to matter whether the top-level context is treated as async or not; if await task.value is replaced with a Thread.sleep call then the precondition begins failing.

1 Like

I found why precondition is not failing while func onMain() reports we are not on Main Actor: the #isolation === MainActor.shared expression evaluates to true in the task, but it is false for some reason[1] in the func onMain() called from the same task, at least on Windows.

That is, both Thread.isMainTread() and #isolation === MainActor.shared behave erratically on Windows, and even not in sync with each other.


  1. Maybe because the function is non-isolated? â†Šī¸Ž

1 Like

This code

import Foundation

func report() {
    print("is main thread = \(Thread.isMainThread); is main actor = \(#isolation === MainActor.shared)")
}

print("is main thread = \(Thread.isMainThread); is main actor = \(#isolation === MainActor.shared)")
report()

let task = Task {
  print("is main thread = \(Thread.isMainThread); is main actor = \(#isolation === MainActor.shared)")
  report()
}

await task.value

gives very amusing output on Windows and Linux[1] :

is main thread = true; is main actor = true
is main thread = true; is main actor = false
is main thread = false; is main actor = true
is main thread = false; is main actor = false

  1. Did not test on a Mac, as I have only Swift 5.9.2 on my older Mac. â†Šī¸Ž