开发者

How do event listeners work?

Do they repeatedly check for the condition and execute if the condition is met. Ex, how the OS knows exactly when a USB device is plugged in, or how MSN knows exactly when you get an email. How does this work?

T开发者_JAVA百科hanks


At the low level, the OS kernel "knows" when something happens, because the device in question sends the CPU a hardware interrupt.

So when, say a network packet arrives, the network controller sends an interrupt, and the OS kernel responds as appropriate.

At the program level, it works quite differently - most application programs run an "event loop", where they fetch a message (say, a message from the OS saying that "the mouse was clicked on this point in your application"), perform the appropriate actions in response to that, and then, listen for more messages. If there is no message, the OS sleeps the thread until it has a message to deliver.


Take a look at Interrupts this should explain how the hardware initiates certain 'events'


Depends.

Often an event listener is registered with the object that generates the event. When the event occurs, the object iterates through all listeners registered with it informing them of the event. Have a look at the AWT/Swing event model in Java for example.

ow the OS knows exactly when it gets a USB

At a low level I suspect thats a hardware interupt (someone correct me if I'm mistaken) which is handled by the kernel/USB driver. There's often higher level systems (e.g. DBUS) that listen for this and have event listeners listening to them.

or how MSN knows exactly when you get an email.

I suspect that's a simple case of polling the mail box (e.g. over POP3) every x seconds and checking the message count (could be wrong though).

Anon. explains the difference between hardware interrupts and software level event listening quite well.


Programs like email checkers will usually be running background services that query their email server every X period checking for new mail. There are other ways of doing it, but for software level events, it's almost certainly going to be something like that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜