1

除了计划运行的队列之外,您能否暂停队列中的 GCD 定时器?

我有一个计时器,在 global_queue 上以低优先级创建,当它触发时,我通过 main_queue 操作一些 UI 工作。对于 UI 中的某些状态,我必须暂停计时器。我是否必须从 main_queue 切换回低优先级队列才能执行挂起?

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);
        });                            
    }
}
4

1 回答 1

2

是的,从任何队列中挂起调度对象都是有效的。如果调用 dispatch_suspend() 时某个块当前正在运行,则该块将完成执行,并且将阻止后续调度的块执行。

于 2011-01-25T23:33:52.823 回答