Asynchronous tasks on Winform

The problem

When you create winform applications, doing tasks in the background is essential to avoid user frustation. Unfortunatly, it could make you write a lot more code. Here are some utility methods that reduce the complexity of asynchronous calls within windows forms.

Within you base class

You probably have a common base class for all your UI components. Add these methods :

Within your UI classes

Now the only thing you need to do is to encapsulate the methode content with the Async() method :

The traditional way

Just in case you didn’t get it. This is what you should NOT DO:

Happy coding !

Make InvokeRequired/Invoke easy

The problem

If you’re working on WinForms, you must know that you cannot call controls methods within a thread that is not the one that created those controls. To solve this problem, Microsoft recommend us to use the following code :

This code is ugly because :

  • you need to create a delegate for each single public method you can call from outside
  • you need to put an “if/else” block in each method wich increase the complexity of your code

The trick

Here is a trick that could significantly reduce the amount of code needed to do the same job within a large project.

Within you base class

You probably have a common base class for all your UI components. Add this method :

Within your UI classes

Now the only thing you need to do is to encapsulate the methode content with the ThreadSafe() method :

Happy coding !