如何立即从Runloop中删除计时器 [英] How to remove timer from runloop immediately

查看:61
本文介绍了如何立即从Runloop中删除计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在5秒钟内触发的计时器添加到全局队列中,尽管我在2秒钟后使运行循环无效,直到5秒钟才终止.在以下代码段中,backgroundTimer是实例var,而run是成员函数.以下代码阻止了运行循环终止,这是怎么回事?

I have a timer triggered in 5 seconds added to global queue, though i am invalidating it after 2 seconds run loop won't terminate till 5 seconds. In the following snippet backgroundTimer is an instance var, and run is a member function. What's wrong in the following code which is blocking the run loop termination.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    _backgroundTimer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(run) userInfo:nil repeats:NO];
    [ [NSRunLoop currentRunLoop] addTimer:_backgroundTimer forMode:NSRunLoopCommonModes];
    [[NSRunLoop currentRunLoop] run];

    NSLog(@"Run loop terminated");

});

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [_backgroundTimer invalidate];
    _backgroundTimer=nil;

});

推荐答案

第一个问题是您的计时器被添加到任意后台线程上的运行循环中.(即该线程将由GCD创建,以服务于后台队列).您可以 做到这一点,但这毫无意义.

The first problem here is that your timer is being added to a run loop on some arbitrary background thread. (i.e. the thread will have been created by GCD to service the background queue) You can do this, but it kind of makes no sense.

此外,您说要发生的事情是退出该运行循环,但是在 -run 方法的文档中,它表示以下内容:

That aside, you said that what you want to have happen is for this run loop to exit, but in the documentation for the -run method, it says the following:

从运行循环中手动删除所有已知的输入源和计时器不能保证运行循环将退出.OS X可以安装和根据需要删除其他输入源以处理目标请求在接收者的线程上.因此,这些来源可能会阻止从退出运行循环.

Manually removing all known input sources and timers from the run loop is not a guarantee that the run loop will exit. OS X can install and remove additional input sources as needed to process requests targeted at the receiver’s thread. Those sources could therefore prevent the run loop from exiting.

如果您想终止运行循环,则不应使用此方法.相反,请使用其他运行方法之一,并检查其他方法循环地建立自己的任意条件.

If you want the run loop to terminate, you shouldn't use this method. Instead, use one of the other run methods and also check other arbitrary conditions of your own, in a loop.

如果您想在计时器无效时退出事件循环,则需要自己旋转事件循环.例如:

You will need to spin the event loop yourself if you want to exit it when the timer is invalid. For example:

while (_backgroundTimer.valid && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow: 0.1]]);

这将使计时器无效后最多0.1(-epsilon)秒退出运行循环.

This will exit the run loop a maximum of 0.1 (- epsilon) seconds after the timer is invalidated.

这篇关于如何立即从Runloop中删除计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆