Get current dispatch queue?

后端 未结 11 1296
难免孤独
难免孤独 2020-12-23 16:28

I have a method which should support being called from any queue, and should expect to.

It runs some code in a background thread itself, and then uses dispatch

11条回答
  •  南笙
    南笙 (楼主)
    2020-12-23 16:50

    With the deprecation of dispatch_get_current_queue() you cannot directly get a pointer to the queue you are running on, however you do can get the current queue's label by calling dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) and that does give you some flexibility.

    You can always check if you are on that specific queue just by comparing their labels, so in your case if you don't want to force it on main queue, when you entered the method you can just utilize the following flag:

    let isOnMainQueue = (dispatch_queue_get_label(dispatch_get_main_queue()) == dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))
    

    If you are running on the global queue, you will respectfully get the queue's label associated with it's QOS type, which can be one of the following:

    com.apple.root.user-interactive-qos //qos_class_t(rawValue: 33)
    com.apple.root.user-initiated-qos   //qos_class_t(rawValue: 25)
    com.apple.root.default-qos          //qos_class_t(rawValue: 21)  
    com.apple.root.utility-qos          //qos_class_t(rawValue: 17)
    com.apple.root.background-qos       //qos_class_t(rawValue: 9) 
    

    And then you can use dispatch_get_global_queue(qos_class_self(), 0) which will give you back that same global queue you are running on.

    But I believe Apple particularly discourages us from bounding the logic to the queue we got called on, so better utilising this for exclusively debugging purposes.

提交回复
热议问题