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

时间:2016-09-03 14:06:40

标签: ios multithreading swift3 nsthread

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

在Swift的早期版本中,通过这样做可以检查当前线程是否是主要线程:

NSThread.isMainThread()

6 个答案:

答案 0 :(得分:151)

在Swift 3中看起来只是Thread.isMainThread

答案 1 :(得分:84)

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

Thread.current将返回您当前的主题。

答案 2 :(得分:12)

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

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

答案 3 :(得分:2)

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)

答案 4 :(得分:1)

在最新的Swift 4.0〜4.2中,我们可以使用Thread.current

请参见Returns the thread object representing the current thread of execution

答案 5 :(得分:0)

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

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