Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does .NET efficiently listen for raised events?

Tags:

c#

.net

events

clr

Does it use some sort of event thread that polls an event queue? Also, does the technique differ depending on the type of event? Some events are raised by the program itself, like a button click, while others are raised externally, like the FileCreated event read by the FileSystemWatcher. Are these events handled differently under the hood?

like image 813
Brian Kraemer Avatar asked Dec 01 '22 00:12

Brian Kraemer


1 Answers

It is a very broad topic, I can only reasonably cover the basics. The mechanisms are not specific to .NET, they apply to any program that runs on Windows. There are two basic ways that the operating system or another program can trigger an event.

The first one is as you assume, the underlying mechanism for a button's Click event as well as almost all of the events that are associated with a GUI program. The core .NET call is Application.Run(), it starts a dispatcher loop. Also known as "pumping the message loop". The general solution to the producer-consumer problem. The basic winapi functions that generate the event are SendMessage() and PostMessage(). A .NET program has plumbing that turn these messages in events that you can subscribe, the NativeWindow class is a good example. Its WndProc() method runs when a message is received. It in turn can then raise a specific event, based on the specific message.

The second one is where the operating system can make a callback to a function on an arbitrary worker thread, usually one pulled from the threadpool. FileSystemWatcher is an example of that one, the underlying winapi function that sets it up is ReadDirectoryChangesW(). It supports overlapped I/O, allowing it to operate asynchronously. In other words, you can ask it to start working on the job and return immediately. The operating system then signals an event or makes a callback when the job is done. Implicit in the way these kind of events work is that they are fired on an arbitrary thread, unlike the first mechanism.

Learning more about the winapi is necessary to make sense of all this.

like image 119
Hans Passant Avatar answered Dec 05 '22 01:12

Hans Passant