I think, as Macs get faster, you need to increase the amount of work for the task. I added a few 0s to the named task’s sum, and it doesn’t finish.
“Task cancelled” would only appear if the task.cancel() executed before the Task closure starts to run.
If you wait long enough, the unnamed task with lots of zeros does finish.
The statement that the named task starts after the unnamed task finishes assumes there are only 2 threads, and that the main thread is reserved for the main actor. But it’s possible for the system to use the main thread for other work, if nothing is happening on the main actor. Or, on a Mac, there are more than 2 processors, so there are more than 2 threads.
Ran into the same issue as well. I tried forcing both tasks to run on the main thread and now task cancellation works as expected since the second task has to wait for the first task to finish, thanks @audrey for the explanation.
Task { @MainActor in
print("\nDoing some work on an unnamed task")
let sum = (1...10000000).reduce(0, +)
print("Unnamed task done: 1 + 2 + 3 ... 100000 = \(sum)")
}
print("Doing some work on the main queue")
print("Doing more work on the main queue")
// This task runs after previous task finishes
let task = Task { @MainActor in
print("\nDoing some work on a named task")
...