Sco*_*des 8 asynchronous async-await swift
我试图弄清楚在异步任务中我所处的线程或运行循环。如何从任务中获取线程或运行循环?
Task {
do {
print("line: ", #line, Thread.current)
let image = try await self.fetchImage()
print("line: ", #line, Thread.current)
} catch {
let fetch: FetchError = error as! FetchError
print("line: ", #line, Thread.current)
}
print("line: ", #line, Thread.current)
}
print("line: ", #line)
Run Code Online (Sandbox Code Playgroud)
当我尝试我的典型方法(即Thread.current)时,我得到:
Class property 'current' is unavailable from asynchronous contexts; Thread.current cannot be used from async contexts.; this is an error in Swift 6.
Run Code Online (Sandbox Code Playgroud)
它仍然在运行,但警告让我相信我不能相信结果。
你的结果可能没问题,但警告也是正确的:你所做的事情是非法的,并且将在 Swift 的未来版本中正式成为非法。因此,从现在开始,不要这样做。
一般来说,在 . 的上下文中根本async/await不要谈论线程。他们对你不感兴趣。你可以要求,Thread.isMainThread但确实如此(除非它现在也有警告;我还没有检查)。就让它async/await做它该做的事并快乐吧。
如果您使用这些print行只是为了了解 async/await 对线程执行的操作,那么一个好的替代方法是NSLog仅使用并输出行号。NSLog自动告诉您线程号作为其输出的一部分,因此根本不需要调用任何 Thread 方法。
| 归档时间: |
|
| 查看次数: |
4109 次 |
| 最近记录: |