The Run Loop Sequence of Eventsoop
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:this
1, Notify observers that the run loop has been entered.spa
2, Notify observers that any ready timers are about to fire.rest
3, Notify observers that any input sources that are not port based are about to fire.server
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. ci
7, Put the thread to sleep until one of the following events occurs:rem
An event arrives for a port-based input source.input
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就会返回。