using dispatch_sync in Grand Central Dispatch

前端 未结 8 2084
孤城傲影
孤城傲影 2020-11-30 17:25

Can anyone explain with really clear use cases what the purpose of dispatch_sync in GCD is for? I can\'t understand where and why I would have to u

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 18:01

    I've used dispatch sync when inside an async dispatch to signal UI changes back to the main thread.

    My async block holds back only a little and I know the main thread is aware of the UI changes and will action them. Generally used this in a processing block of code that takes some CPU time but I still want to action UI changes from within that block. Actioning the UI changes in the async block is useless as UI, I believe, runs on the main thread. Also actioning them as secondary async blocks, or a self delegate, results in the UI only seeing them a few seconds later and it looks tardy.

    Example block:

    dispatch_queue_t myQueue = dispatch_queue_create("my.dispatch.q", 0);
    dispatch_async(myQueue,
    ^{
    
        //  Do some nasty CPU intensive processing, load file whatever
    
             if (somecondition in the nasty CPU processing stuff)
             {
                 //  Do stuff
                 dispatch_sync(dispatch_get_main_queue(),^{/* Do Stuff that affects UI Here */});
             }
    
     });
    

提交回复
热议问题