문제

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

I have a timer, 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top