开发者

Memory leaks when generating dispatch source timer events

We are using dispatch queues to generate timer events. Following is the code which does the task:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
if (!timer) return self;
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval * NSEC_PER_SEC, 5 * NSEC_PER_SEC);

dispatch_source_set_event_handler(timer, 
^{
    //Some work…
});

This works very well except that when we run the profiler, we see a lot of memory leaks from these methods:

  • dispatch_source_create
  • dispatch_source_set_timer
  • dispatch_source_set_event_handler

We had made sure that timer is released using dispatch_release() method.

Can someone please let us know if there is any mistake we are doing in the code above? And 开发者_开发知识库also if you can point out any example of timer event generation, it would be helpful.


dispatch_source_set_timer(3) Mac OS X Manual Page

All timers will repeat indefinitely until dispatch_source_cancel() is called.

How do you call dispatch_source_cancel() and dispatch_release() for the timer?

Dispatch source timer example:

dispatch_source_t timer = dispatch_source_create(
    DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));

dispatch_source_set_timer(timer,
    dispatch_time(DISPATCH_TIME_NOW, 1ull * NSEC_PER_SEC),
        DISPATCH_TIME_FOREVER, 1ull * NSEC_PER_SEC);

dispatch_source_set_event_handler(timer, ^{
    NSLog(@"wakeup!");

    dispatch_source_cancel(timer);
});

dispatch_source_set_cancel_handler(timer, ^{
    NSLog(@"canceled");

    dispatch_release(timer);
});

dispatch_resume(timer);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜