开发者

suspending dispatch timers from main_queue when it was created on another one

开发者 https://www.devze.com 2023-02-07 04:52 出处:网络
Can you suspend a GCD timer from a queue besides the one it\'s schedule to run on? I have a time开发者_如何学Cr, created on the global_queue with low priority and when it fires, I manipulate some UI

Can you suspend a GCD timer from a queue besides the one it's schedule to run on?

I have a time开发者_如何学Cr, created on the global_queue with low priority and when it fires, I manipulate some UI work via the main_queue. For some states in the UI, I have to suspend the timer. Do I have to switch from the main_queue back to the low priority queue to perform the suspend?

dispatch_queue_t lowPriQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);   
myTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, lowPriQ);        

dispatch_source_set_timer(myTimer, 
                          startTime, // now
                          interval, // 15 seconds
                          2000ull); 

// configure the event handler
dispatch_source_set_event_handler(myTimer, ^{           
    NSLog(@"Timer fired");

    // UI Work
    dispatch_async(dispatch_get_main_queue(), ^ {
            [self doSomeButtonEnableDisable]
    });                        
});

dispatch_resume(myTimer); // start the timer

- (void)doSomeButtonEnableDisable
{
    if (someParticularState) {
        // Turn off the timer 

        // Should I suspend the timer on the low priority global queue
        // or is it valid to suspend on the main queue?

        dispatch_queue_t lowPriQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);   

        dispatch_async(lowPriQ(), ^ {

            dispatch_suspend(myTimer);
        });                            
    }
}


Yes, it's valid to suspend a dispatch object from any queue. If a block is currently running when dispatch_suspend() is called, that block will complete execution and subsequent scheduled blocks will be prevented from executing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号