gpt4 book ai didi

swift - 类属性 'current' 在异步上下文中不可用; Thread.current 不能在异步上下文中使用。这是 Swift 6 中的一个错误

转载 作者:行者123 更新时间:2023-12-02 15:47:06 25 4
gpt4 key购买 nike

我试图弄清楚在异步任务中我在哪个线程或运行循环上。如何从任务中获取线程或运行循环?

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)

当我尝试我的典型方法(即 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.

它仍然运行,但警告让我相信我不能相信结果。

最佳答案

你的结果可能没问题,但警告也是正确的:你所做的是非法的,并且在未来的 Swift 版本中将正式成为非法的。因此,从现在开始不要这样做。

一般来说,async/await 的上下文中不要谈论线程。他们对你不感兴趣。您可以请求 Thread.isMainThread 但实际上就是这样(除非它现在也有警告;我还没有检查过)。只需让 async/await 做它的事情并且开心。

如果你使用这些 print 行只是为了了解 async/await 对线程做了什么,一个好的选择是使用 NSLog 和输出只有行号。 NSLog 会自动告诉您线程号作为其输出的一部分,因此根本不需要调用任何 Thread 方法。

关于swift - 类属性 'current' 在异步上下文中不可用; Thread.current 不能在异步上下文中使用。这是 Swift 6 中的一个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73790307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com