Asynchrony and .NET events? Asynchrony and .NET events? multithreading multithreading

Asynchrony and .NET events?


Let me shed some light on your problem. The magic is the windows message loop. You see in your example, actually, there is nothing making Code A stop when an event occurs. Rather, this is the sequence.

When code A is running, the user clicks on a button. The button's window message gets queued, but nothing happens. When code A exits its function or relinquishes control back to the message loop, then the Click event is processed and the Event Handler is run.

Try this experiment. Put an infinity loop inside your program on the main thread and then click on the user interface. You will notice that the user interface will be unresponsive and there will be no Event Handlers running.


The thing you will see from 20,000 feet is the MessageLoop. It is inside Application.Run().

Simply stated, this is a while-loop that runs the entire lifetime of your app and does

  // pseudo code, I did not reflector Application.Run  while (GetMessage(ref msg)  {     DispatchMessage(ref msg);  }

You will notice the simgle-thread when you take too long handling 1 event, your app will be labeled 'nonresponsive' in TaskManager.

A related method is Application.DoEvents(), but stay away from that.


Events are pointers to functions (just like we used to have in C++). When you use plain vanilla .NET event you're actually calling the functions that are connected using += to that event. So from 20,000 feet your code actually calls some other code just like calling another function.This is why it's called synchronously and in the same thread.

When inside WinForms/WPF control we also have a message loop to consider:All events that occurs within the context of the form adds a message to the message loop instead of calling a method directly.

The main thread of the control polls that loop for new messages and when a new message appears he executes it (again in the main thread) only now it's not exactly synchronous.

This is the reason that if a form is busy doing something and you press a button it takes some time before that button is pressed. this is also the reason that if you invalidate a control it's appearance is only changed after you exit the running method (and the next message is processed).