如何在Swift 3中检查当前线程?


105

如何检查Swift 3中的当前线程是哪个?

在以前的Swift版本中,可以通过执行以下操作检查当前线程是否为主线程:

NSThread.isMainThread()

Answers:



106

Thread.isMainThread将返回一个布尔值,指示您当前是否在主UI线程上。但这不会给您当前的线程。它只会告诉您是否处于主要状态。

Thread.current 将返回您所在的当前线程。


24

我做了一个扩展来打印线程和队列:

extension Thread {
    class func printCurrent() {
        print("\r⚡️: \(Thread.current)\r" + "🏭: \(OperationQueue.current?.underlyingQueue?.label ?? "None")\r")
    }
}

Thread.printCurrent()

结果将是:

⚡️: <NSThread: 0x604000074380>{number = 1, name = main}
🏭: com.apple.main-thread

16

Swift 4及更高版本:

Thread.isMainThread返回Bool说明用户是否在主线程上,如果有人要打印队列/线程的名称,此扩展名将很有帮助

extension Thread {

    var threadName: String {
        if let currentOperationQueue = OperationQueue.current?.name {
            return "OperationQueue: \(currentOperationQueue)"
        } else if let underlyingDispatchQueue = OperationQueue.current?.underlyingQueue?.label {
            return "DispatchQueue: \(underlyingDispatchQueue)"
        } else {
            let name = __dispatch_queue_get_label(nil)
            return String(cString: name, encoding: .utf8) ?? Thread.current.description
        }
    }
}

如何使用:

print(Thread.current.threadName)

9

使用GCD时,可以使用dispatchPrecondition来检查进一步执行所需的调度条件。如果您想保证代码在正确的线程上执行,这将很有用。例如:

DispatchQueue.main.async {
    dispatchPrecondition(condition: .onQueue(DispatchQueue.global())) // will assert because we're executing code on main thread
}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.