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

Viewed 40

I am trying to figure out what thread or run loop I am on when in an async task. How can I get the thread or run loop from a task?

        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)

When I try my typical method, I get:

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

It still runs, but the warning makes me believe I can't trust the result.

1 Answers

Your result is probably okay, but the warning is right too: what you're doing is illegal, and will be made formally illegal in a future version of Swift. So start now by not doing it.

In general, do not speak of threads at all in the context of async/await. They are of no interest to you. You can ask for Thread.isMainThread but that's really it (unless it too now has a warning; I haven't checked). Just let async/await do its thing and be happy.

If you're using these print lines just to get a sense for what async/await is doing with threads, a good alternative would be to use NSLog and output the line number only. NSLog automatically tells you thread number as part of its output, so no need to call any Thread methods at all.

Related