How to dispatch on main queue synchronously without a deadlock?

前端 未结 3 1403
盖世英雄少女心
盖世英雄少女心 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:13

    I need to use something like this fairly regularly within my Mac and iOS applications, so I use the following helper function (originally described in this answer):

    void runOnMainQueueWithoutDeadlocking(void (^block)(void))
    {
        if ([NSThread isMainThread])
        {
            block();
        }
        else
        {
            dispatch_sync(dispatch_get_main_queue(), block);
        }
    }
    

    which you call via

    runOnMainQueueWithoutDeadlocking(^{
        //Do stuff
    });
    

    This is pretty much the process you describe above, and I've talked to several other developers who have independently crafted something like this for themselves.

    I used [NSThread isMainThread] instead of checking dispatch_get_current_queue(), because the caveats section for that function once warned against using this for identity testing and the call was deprecated in iOS 6.

提交回复
热议问题