簡體   English   中英

如何在 Swift 3 中查看當前線程?

[英]How to check current thread in Swift 3?

如何查看Swift 3中的當前線程是哪一個?

在 Swift 的早期版本中,可以通過以下方式檢查當前線程是否是主線程:

NSThread.isMainThread()

看起來它只是Swift 3中的Thread.isMainThread

Thread.isMainThread將返回一個布爾值,指示您當前是否在主UI線程上。 但這不會給你當前的線程。 它只會告訴你你是否在主要。

Thread.current將返回您當前的線程。

Swift 5+

通常情況下,我們只需要知道代碼被調度到哪個隊列即可。 所以我把threadNamequeueName到不同的屬性中,以使其更清晰。

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

我做了一個擴展來打印線程和隊列:

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

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)

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

請參見返回表示當前執行線程的線程對象

使用GCD時,您可以使用dispatchPrecondition檢查進一步執行所需的調度條件。 如果您想保證在正確的線程上執行代碼,這將非常有用。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM