这是苹果开发者文档中的代码。</p>
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"
}
}
}
为什么不在message
UI 线程中更新如下代码
DispatchQueue.main.async {
message = "Received \(receivedLines.count) lines"
}
任务块中的代码是否总是在 UI 线程中运行?
这是我的测试代码。有时似乎任务没有继承其调用者的参与者上下文。
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("")
任务中的线程前后不同wait()
任务中的线程不是Main thread