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

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

问题描述

我有一个任务需要每1秒执行一次。目前我有一个NSTimer每1秒重复发射。

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天全站免登陆