【问题标题】:Class property 'current' is unavailable from asynchronous contexts; Thread.current cannot be used from async contexts.; this is an error in Swift 6类属性 \'current\' 在异步上下文中不可用; Thread.current 不能在异步上下文中使用。;这是 Swift 6 中的错误
【发布时间】:2022-10-04 16:31:11
【问题描述】:

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

        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)

当我尝试我的典型方法时,我得到:

// Class property 'current' is unavailable from asynchronous contexts; Thread.current cannot be used from async contexts.; this is an error in Swift 6.

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

【问题讨论】:

  • 看看仪器。在 Xcode 14 中,线程的可视化比print 行方便得多。

标签: swift asynchronous async-await


【解决方案1】:

你的结果可能没问题,但警告也是正确的:你所做的事情是非法的,并且在未来的 Swift 版本中将被正式规定为非法。所以现在从不做开始。

一般来说,不要说线程根本async/await 的上下文中。他们对你没有兴趣。

你可以要求Thread.isMainThread 但就是这样(除非它现在也有警告;我还没有检查). 它还发出警告:Class property 'isMainThread' is unavailable from asynchronous contexts; Work intended for the main actor should be marked with @MainActor; this is an error in Swift 6

async/await 做它的事并快乐。

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

【讨论】:

  • 你没有在你的问题中解释为什么你思考知道这是否是主线程对你来说很重要,所以你的问题可能是一个 XY 问题。不过,我回答的是你的问题做过问。
  • 我通常会尝试了解异步等待以及程序执行的流程以及原因。
  • 很酷,所以现在你可以继续使用你的代码并接受警告。无论如何,您将删除运输代码中的 print 语句。但根据我的经验,询问这是否是主线程是全部您需要知道以检查 async/await 正在做什么。
  • 或者,您可以使用 NSLog;它会自动免费告诉你这是什么线程什么您选择打印。我会将其添加到我的答案中。
猜你喜欢
  • 1970-01-01
  • 2021-06-25
  • 2018-11-13
  • 2022-11-16
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多