我正在努力学习快速并发,但它带来了很多困惑.据我所知,任务{}是一个异步单元,它将允许我们从同步上下文中桥接异步函数调用.它类似于DispatchQueue.Global(),后者将在某个任意线程上执行该块.
override func viewDidLoad() {
super.viewDidLoad()
Task {
do {
let data = try await asychronousApiCall()
print(data)
} catch {
print("Request failed with error: \(error)")
}
}
for i in 1...30000 {
print("Thread \(Thread.current)")
}
}
下面是我的AsychronousApiCall函数
func asychronousApiCall() async throws -> Data {
print("starting with asychronousApiCall")
print("Thread \(Thread.current)")
let url = URL(string: "https://www.stackoverflow.com")!
// Use the async variant of URLSession to fetch data
// Code might suspend here
let (data, _) = try await URLSession.shared.data(from: url)
return data
}
当我try 这个实现时.我总是看到,在for loop
完成之后,打印出"Start with asychronousApiCall",线程是MainThread.
就像这样
Thread <_NSMainThread: 0x600000f10500>{number = 1, name = main}