如何在后台线程上创建 NSTimer? [英] How do I create a NSTimer on a background thread?

查看:26
本文介绍了如何在后台线程上创建 NSTimer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务需要每 1 秒执行一次.目前我有一个 NSTimer 每 1 秒重复触发一次.如何在后台线程(非 UI 线程)中触发计时器?

I have a task that needs to be performed every 1 second. Currently I have an NSTimer firing repeatedly every 1 sec. How do I have the timer fire in a background thread (non UI-thread)?

我可以让 NSTimer 在主线程上触发,然后使用 NSBlockOperation 来调度后台线程,但我想知道是否有更有效的方法来做到这一点.

I could have the NSTimer fire on the main thread then use NSBlockOperation to dispatch a background thread, but I'm wondering if there is a more efficient way of doing this.

推荐答案

定时器需要安装到运行在已经运行的后台线程上的运行循环中.该线程必须继续运行运行循环才能真正触发计时器.为了让后台线程继续能够触发其他计时器事件,它需要产生一个新线程来实际处理事件(当然,假设您正在执行的处理需要大量时间).

The timer would need to be installed into a run loop operating on an already-running background thread. That thread would have to continue to run the run loop to have the timer actually fire. And for that background thread to continue being able to fire other timer events, it would need to spawn a new thread to actually handle events anyway (assuming, of course, that the processing you're doing takes a significant amount of time).

无论如何,我认为通过使用 Grand Central Dispatch 或 NSBlockOperation 生成新线程来处理计时器事件是对主线程的完全合理的使用.

For whatever it's worth, I think handling timer events by spawning a new thread using Grand Central Dispatch or NSBlockOperation is a perfectly reasonable use of your main thread.

这篇关于如何在后台线程上创建 NSTimer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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