Take the 2-minute tour ×

This is a general topic, How do Event Handlers work?

This means behind the scenes - what happens when they are created.

I have a rough idea - but would like to have it confirmed.

share|improve this question
Brilliant, the Observer pattern was what I had found:I have had a read around the web regarding this issue and read a good paper on the subject of Event Driven Programming. Within this paper it discusses the process of the Handlers Design Pattern. Whereby you have a steam of Events that come to a Dispatcher which then take that event and analyse it to determine its event type, and then send each event to a handler that can handle events of that type. –  JHarley1 Jan 5 '11 at 16:47
It explains how the dispatcher it an infinite loop that only stops when (for example with a GUI Application) the program is closed. And then how you have an Observer Pattern (or the Publish/Subscribe Pattern) which is widely used to do Event-Driven Programming with GUI frameworks and how it works on the Hollywood principle of "Don't Call Us We'll Call You". –  JHarley1 Jan 5 '11 at 16:48
Would you say the above explanation is adequate? –  JHarley1 Jan 5 '11 at 16:51
It depends. For a high level overview, it is fine. However, for a comprehensive and thorough explanation, heck no. Course such an explanation would likely be many pages of work as this can be rather fancy as you could get into web vs desktop event stuff for example. –  JB King Jan 5 '11 at 17:07

1 Answer 1

up vote 10 down vote accepted

On a low-level, event handlers often work by polling a device and waiting for a hardware interrupt. Essentially, a background thread blocks, while waiting for a hardware interrupt to occur. When an interrupt occurs, the poll function stops blocking. The application can then find out which device handle caused the interrupt, and what type of interrupt it was, and then act accordingly (e.g. by invoking an event handler function). This is usually done in a separate thread so that it happens asynchronously.

Of course, the way this is actually implemented varies considerably depending on the OS and the type of device/input. On UNIX systems, one way that event handlers are implemented for things like sockets, serial or USB ports is through the select or poll system calls. One or more file/device descriptors (which are associated with a device, like a network socket, serial/USB port, etc) are passed to the poll system call - which is made available to the programmer through a low-level C API. When an event occurs on one of these devices, (like say, some data arrives on a serial port), the poll system call stops blocking, and the application can then determine which device descriptor caused the event, and what type of event it was.

On Windows this is handled differently, but the concepts are basically the same.

share|improve this answer

Your Answer


