How to dispatch on main queue synchronously without a deadlock?

前端 未结 3 1409
盖世英雄少女心
盖世英雄少女心 2020-11-29 16:44

I need to dispatch a block on the main queue, synchronously. I don’t know if I’m currently running on the main thread or no. The naive solution looks like this:



        
3条回答
  •  甜味超标
    2020-11-29 17:00

    For syncing on the main queue or on the main thread (that is not the same) I use:

    import Foundation
    
    private let mainQueueKey    = UnsafeMutablePointer.alloc(1)
    private let mainQueueValue  = UnsafeMutablePointer.alloc(1)
    
    
    public func dispatch_sync_on_main_queue(block: () -> Void)
    {
        struct dispatchonce  { static var token : dispatch_once_t = 0  }
        dispatch_once(&dispatchonce.token,
        {
            dispatch_queue_set_specific(dispatch_get_main_queue(), mainQueueKey, mainQueueValue, nil)
        })
    
        if dispatch_get_specific(mainQueueKey) == mainQueueValue
        {
            block()
        }
        else
        {
            dispatch_sync(dispatch_get_main_queue(),block)
        }
    }
    
    extension NSThread
    {
        public class func runBlockOnMainThread(block: () -> Void )
        {
            if NSThread.isMainThread()
            {
                block()
            }
            else
            {
                dispatch_sync(dispatch_get_main_queue(),block)
            }
        }
    
        public class func runBlockOnMainQueue(block: () -> Void)
        {
            dispatch_sync_on_main_queue(block)
        }
    }
    

提交回复
热议问题