UI Threading Helper Classes

Introduction

One of the most cumbersome things you will ever have to do with Winforms is updating your User interface while receiving events from another thread. For example, you have a long-running method, but you want to show a progress bar while it runs. To make the application responsive during execution of this method, you decide to run the method in a new Thread. No problems! However, you can't just call methods on the progress bar control from the running method. The reason lies in the fact that the Progress bar is part of the Form thread, which is different from the Method thread. Calling methods on another thread can lead to application hangs and other great stuff.

The only way to call methods on the progress bar control is by calling the Form.Invoke() method, which takes a delegate to a method which would perform this operation. Form.Invoke() performs the invocations using the Form's thread, which is the "good" way to perform these operations.

This means that every time you want to update your UI from another thread, you'd need to create 2 separate methods and 2 separate delegates. One method and delegate to recieve the event from the thread which then " Invoke "s another delegate to a method on the form, whcih actually updates the UI. Agh . Isn't that wonderful?

You might also like...

Comments

Roy Osherove Roy Osherove has spent the past 6+ years developing data driven applications for various companies in Israel. He's acquired several MCP titles, written a number of articles on various .NET topics, ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“UNIX is basically a simple operating system, but you have to be a genius to understand the simplicity.” - Dennis Ritchie