In general how do Event Handlers work

event-programmingimplementations

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.

Best Answer

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.

Related Topic