It is high time we threw old Background Worker and got used to the new .NET 4.5 Async

- Emran Hussain,
14 April 2013, Sunday, 12:18:31 PM

.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.

use_caseRandom_ Number_ Generator_ GUI

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.

random_generator_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.

code_part_first

Run_ Click_event_handler

code_part 3

To visualize the Run button operation here is a Sequence Diagram.

run_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.

Thank you.

© All content, photographs, graphs and images in this article are copyright protected by SpiceLogic Inc. and may not, without prior written authorization, in whole or in part, be copied, altered, reproduced or published without exclusive permission of its owner. Unauthorized use is prohibited.
Last edited on : 5 Dec 2016
Please feel free to share your comment.