除了计划运行的GCD计时器之外,你能暂停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);
});
}
}
答案 0 :(得分:1)
是的,从任何队列挂起调度对象都是有效的。如果在调用dispatch_suspend()时当前正在运行一个块,则该块将完成执行,并且将阻止后续调度的块执行。