RunLoop 事件处理过程


The Run Loop Sequence of Events

Each time you run it, your thread’s run loop processes pending events and generates notifications for any attached observers. The order in which it does this is very specific and is as follows:

1, Notify observers that the run loop has been entered.

2, Notify observers that any ready timers are about to fire.

3, Notify observers that any input sources that are not port based are about to fire.

4, Fire any non-port-based input sources that are ready to fire.

5, If a port-based input source is ready and waiting to fire, process the event immediately. Go to step 9.

6, Notify observers that the thread is about to sleep. 

7, Put the thread to sleep until one of the following events occurs:

  • An event arrives for a port-based input source.

  • A timer fires.

  • The timeout value set for the run loop expires. 

  • The run loop is explicitly woken up. 

8, Notify observers that the thread just woke up. 

9,Process the pending event.

  • If a user-defined timer fired, process the timer event and restart the loop. Go to step 2.

  • If an input source fired, deliver the event.

  • If the run loop was explicitly woken up but has not yet timed out, restart the loop. Go to step 2. 

10, Notify observers that the run loop has exited. 


从 步骤2 到 步骤9 称为 一个 loop

另外注意fire source 和 deliver event的区别: 

    fire xx source 的意思是将该 source 加入监听队列,因为可以随时add 和 remove source ,所以每次loop 都要处理;

    deliver event 就是调度、处理source 触发的event。


从整个过程可以看出,

  •     Port-based input source 事件优先级是最高的,port-based source 注册后会马上执行,但是port event 并不屏蔽其他事件,处理完 port event 可以在同一个loop中继续处理其它事件(Timer 、 custom、 selector)

  •     Timer事件比较特殊, 从第九步可以看出每次 系统timer(non-user-defined timer) 事件触发后,会导致loop从新开始,其余事件(custom、 selector)只能在新的loop得到处理机会;

  •     Timer 事件 和 port 事件可以唤醒 休眠的runloop, 但是其他input source 事件不具有这个功能, 所以在自己写的input source 执行完 CFRunLoopSourceSignal(runLoopSource) 发消息操作后, 还要执行  CFRunLoopWakeUp(runloop) 把 runloop 唤醒, 这样消息才能得到及时处理

  •     runMode:beforeDate方法执行一次,内部可能发生 1次 或 多次loop

  •     除了Port-based event 和 Timer event, RunLoop 的 runMode:beforeDate 方法每次处理完一个 input source 事件(包括custom 、selector)或者time out就会返回。



转载于:https://my.oschina.net/u/255456/blog/522672

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值