我面臨着一些奇怪的Grand Central Dispatch計時器行爲。它打破了它的射擊時間並凍結了很多秒。雖然我需要ping我的服務器以保持「在線」狀態,但這種行爲非常不合適。奇怪的GCD計時器行爲
這裏是計時器的創建代碼。
// pingTimer and pingQueue are class members
- (void)createPingTimerSource
{
// check timer exists
if(pingTimer)
{
// suspend source and cancel
[self setPingTimerSuspended:YES];
dispatch_source_cancel(pingTimer);
}
// check having queue, create if doesn't exist
if(!pingQueue)
pingQueue = dispatch_queue_create(kDispatchTimerQueueLabel, NULL);
// create timer dispatch source
pingTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, pingQueue);
dispatch_source_set_timer(pingTimer, dispatch_time(DISPATCH_TIME_NOW, 5*NSEC_PER_MSEC), 5*NSEC_PER_MSEC, NSEC_PER_SEC/10);
// set event handler
dispatch_source_set_event_handler(pingTimer,^{
printf("[%llu] gcd timer fired.\n", mach_absolute_time()/NSEC_PER_SEC);
dispatch_async(dispatch_get_main_queue(), ^{
[self sendPingToServer];
});
});
// set cancel handler
dispatch_source_set_cancel_handler(pingTimer, ^{
// release dispatch source if exists
if(pingTimer)
dispatch_release(pingTimer);
// check timer queue exists and release if does
if(pingQueue)
dispatch_release(pingQueue);
});
}
這裏是日誌控制檯的鏡頭。
謝謝你的幫助。
是的,你說得對。謝謝你的幫助! – Astoria 2014-11-04 09:24:36