I m 曲解为什么Task C和Task D? 与Task A和Task B不同,在主线上不执行。 我理解,任务由父母继承,在这种情况下,他们都与父母相同。 可以假定,电话功能产生detastal>。 任务?
struct ThreadTestView: View {
var body: some View {
Text("Test Thread")
.onAppear {
// Task A
print("Task A - (threadInfo())")
// Task B
Task {
print("Task B - (threadInfo())")
}
// Task C
printInfo("Task C")
// Task D
Task {
printInfo("Task D")
}
}
}
func printInfo(_ source: String) {
Task {
print("(source) - (threadInfo())")
}
// detached
Task.detached {
print("(source) - detached (threadInfo())")
}
}
func threadInfo() -> String {
"isMain:(Thread.isMainThread) - (Thread.current)"
}
}
#Preview {
ThreadTestView()
}
青少年产出:
Task A - isMain:true - <_NSMainThread: 0x280694040>{number = 1, name = main}
Task C - isMain:false - <NSThread: 0x2806c6b00>{number = 8, name = (null)}
Task C - detached isMain:false - <NSThread: 0x2806c4580>{number = 5, name = (null)}
Task B - isMain:true - <_NSMainThread: 0x280694040>{number = 1, name = main}
Task D - isMain:false - <NSThread: 0x2806c6b00>{number = 8, name = (null)}
Task D - detached isMain:false - <NSThread: 0x2806c6b00>{number = 8, name = (null)}