When writing a multi threaded Windows Forms application, it is very important to make all changes to the controls inside the UI Thread. This is nothing new and the solution can be found on MSDN and in a lot of blogs: Some controls are taking care for us already. A good example can be the BackgroundWorker with the ProgressChanged and RunWorkerCompleted events.
As soon as these offered solutions are not suitable, the developer starts to check InvokeRequired and, if required, the invoke is called.
This can end up in a lot of coding. And often it is simply not required. When subscribing to an event, it is most of the time known, if the event is fired from another thread or not. So when I want to subscribe to an event in a Windows Forms application, that is fired by another thread, I already know: an invoke is required.
Here the new functions of C# are very nice, because I can get rid of all the InvokeRequired checks. The subscription could directly be done like this:
someObject.AnEvent += ((sender, args) => Invoke(new EventHandler<TheEventArgs>(MyFunction), sender, args));
- sender, args: lamda identifiers
- someObject is an instance of any class that defines an event and where I expect that the event is fired by some other thread.
- AnEvent is an event that has TheEventArgs as Parameter
- TheEventArgs derives from EventArgs and is the type of the event argument.
- MyFunction is the function that should handle the event with this signature:
void MyFunction(object sender, TheEventArgs e)
I hope this was an interesting topic. One small disadvantage is, that the anonymous function is not available to remove the listener cleanly from the event. (In this Windows Forms topic it should not be that important. Before closing a Form you will take care of all threads / business objects connected to the form.)
Feel free to send me your feedback. Either use this page directly or send me a message at email@example.com