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

问题描述 投票:0回答:7

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

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

NSThread.isMainThread()
ios multithreading swift3 nsthread
7个回答
286
投票

看起来就像 Swift 3 中的

Thread.isMainThread
一样。


142
投票

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

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


42
投票

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

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

还建议使用(不适用于异步/等待代码):

extension DispatchQueue {
    /// - Parameter closure: Closure to execute.
    func dispatchMainIfNeeded(_ closure: @escaping VoidCompletion) {
        guard self === DispatchQueue.main && Thread.isMainThread else {
            DispatchQueue.main.async(execute: closure)
            return
        }

        closure()
    }
}

DispatchQueue.main.dispatchMainIfNeeded { ... }

33
投票

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)

17
投票

斯威夫特5+

通常情况下,我们只需要知道代码被调度到哪个队列即可。所以我将

threadName
queueName
分成不同的属性,以便更清晰。

extension Thread {
    var threadName: String {
        if isMainThread {
            return "main"
        } else if let threadName = Thread.current.name, !threadName.isEmpty {
            return threadName
        } else {
            return description
        }
    }
    
    var queueName: String {
        if let queueName = String(validatingUTF8: __dispatch_queue_get_label(nil)) {
            return queueName
        } else if let operationQueueName = OperationQueue.current?.name, !operationQueueName.isEmpty {
            return operationQueueName
        } else if let dispatchQueueName = OperationQueue.current?.underlyingQueue?.label, !dispatchQueueName.isEmpty {
            return dispatchQueueName
        } else {
            return "n/a"
        }
    }
}

使用案例:

DispatchQueue.main.async {
   print(Thread.current.threadName)
   print(Thread.current.queueName)
}
// main
// com.apple.main-thread
DispatchQueue.global().async {
   print(Thread.current.threadName)
   print(Thread.current.queueName)
}
// <NSThread: 0x600001cd9d80>{number = 3, name = (null)}
// com.apple.root.default-qos

13
投票

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

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

5
投票

在最新的 Swift 4.0 ~ 4.2 中,我们可以使用

Thread.current

参见 返回代表当前执行线程的线程对象

© www.soinside.com 2019 - 2024. All rights reserved.