.NET 4.5 has arrived. The most significant feature of this .NET Framework version is it's Asynchronous programming feature. We do not need to write Spaghetti code anymore for asynchronous programming. Even though, it may not be comfortable and practical to upgrade all legacy code to .net 4.5 async, still I find it highly tempting to replace old Background worker based Spaghetti code to new .NET 4.5 async. When we think about learning asynchronous programming, there are several things we look for,..... How to cancel the task, how to update a UI as progress change... Etc. So, I have organized these usages in a complete little application that I have attached here. This article will not discuss all the details about async feature of .NET 4.5, rather, this article will present you a simple working model so that you can quickly upgrade your old Background worker based application to the async based application., it is for programmers who already understand code syntax, and don't have time to learn all the details about async feature of .net 4.5 before upgrading their code from Background worker to async. It is really worth upgrading, as you can apply more patterns to your code, organize cohesive responsibilities into a single method, instead of scattering here and there. In this article, I have chosen Windows Form platform to demonstrate this feature.
The attached sample application is programmed to do a very simple task. Here is the Use Case.
It will Generate a new Random number at random interval. I have used Thread. Sleep (..) for simulating long, time-consuming task. Here is the screenshot of the User Interface of my sample application when running.
The Run button will call the async operation, which is generating a random number and append that number to the List Box shown in the User Interface. The Cancel Button will cancel the operation, and there is a progress bar which will show the total number of calls made by the program after hitting the Start button.
Here is the snapshot of the source code (code behind file of this Form). The full source code is attached.
To visualize the Run button operation here is a Sequence Diagram.
I hope, this model can help you to upgrade the asynchronous code in your legacy application. Please feel free to comment your concerns.