Here is the code in Apple developer document。
let url = URL(string: "https://example.com")!
@State private var message = "Loading..."
var body: some View {
Text(message)
.task {
do {
var receivedLines = [String]()
for try await line in url.lines {
receivedLines.append(line)
message = "Received \(receivedLines.count) lines"
}
} catch {
message = "Failed to load"
}
}
}
Why don't it update message
in the UI thread as code below
DispatchQueue.main.async {
message = "Received \(receivedLines.count) lines"
}
Does the code in task block alway run in the UI thread?
Here is my test code. It sometimes seems that task isn't inherit the actor context of its caller.
func wait() async {
await Task.sleep(1000000000)
}
Thread.current.name = "Main thread"
print("Thread in top-level is \(Thread.current.name)")
Task {
print("Thread in task before wait is \(Thread.current.name)")
if Thread.current.name!.isEmpty {
Thread.current.name = "Task thread"
print("Change thread name \(Thread.current.name)")
}
await wait()
print("Thread in task after wait is \(Thread.current.name)")
}
Thread.sleep(until: .now + 2)
// print as follow
// Thread in top-level is Optional("Main thread")
// Thread in task before wait is Optional("")
// Change thread name Optional("Task thread")
// Thread in task after wait is Optional("")
Thread in task is different before and after wait()
Thread in task is not Main thread