Events in multithreaded Windows Forms applications.

You can get a PDF with this article and the code is part of my blog solution available at https://neitzel.de:4443/svn/Blog.

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:

Syntax:

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 konrad@neitzel.de

Konrad Neitzel

Advertisements
This entry was posted in Software Development. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s