Asynchronous programming in C#

 Sep 23, 2014

One of the most interesting new features in C# 5.0 is the support for asynchronous functions with the introduction of the new keywords, async and await. Writing asynchronous code was much more complex before the introduction of these amazing keywords. The main scenario for asynchronous programming is the improvement of the perceived performance of your application by distributing the processing across multiple threads without blocking the main thread where the UI is running. The user remains in control of the UI during the execution of long-running operations in the back end. Another important scenario is to run CPU intensive calculations faster in those cases where it is possible to divide the workload in parallel threads that would run simultaneously in different cores in a multi-core machine. You can use the async modifier in the declaration of a method to indicate that the method is asynchronous.
public async void DoTaskAsync(…) { … }
Within the async method, you can use the await operator to indicate points at which the execution of the method can be suspended while you wait for a long-running operation to return, as for example calling some IO operation.
StorageFile file1 = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
When the above statement is encountered, the execution returns to the caller of the async method DoTaskAsync, but immediately before that the runtime attaches a continuation Task containing the remaining of the DoTaskAsync method. When the execution of the awaited operation completes the execution jumps back into your async method and continues where it left off. You can have as many awaited calls inside an async method as needed. You certainly could start the threads explicitly and use callbacks to encapsulate the code to run when the thread completes, but if the code to run also has to repeat the same pattern you would have nested callbacks making the code much more involved to write. The plumbing is provided automatically by simply declaring the method as async and using the await operator as many times as required. The caller of the DoTaskAsync will have to use the await operator to invoke the method. If the caller is some event handler in the UI, as for example the click event handler of a button, you have to add the async keyword to the declaration.
private async void EditItemButton_Click(object sender, RoutedEventArgs e) { await DoTaskAsync(…); … }
Note that your async method returns void. In those cases where there is something to be returned, say a string for example, you have to declare the return as a Task.
public async Task DoTaskAsync(…) { … }
Now you could call the method and store the return in a variable:
string result = await DoTaskAsync(…);
As you can see, writing asynchronous functions couldn’t be made easier than that. Of course, we have just covered the simplest case of writing the code. For a much more in depth coverage of this feature, I recommend New Horizons’ 20483 – Programming in C# training program.

How do your Excel skills stack up?   

Test Now  

About the Author:

Newton Godoy  

With over 17 years of in-class training experience and over 16 years of industry experience, Newton offers students a wealth of real-world technical knowledge and expertise in the areas of .NET application development, SQL Server and SharePoint Server. After spending several years lecturing as a professor, Newton found his true calling and began his career as a MCT. He worked as a technical trainer for some of Brazil’s and Australia’s largest corporate training organisations before finally finding a home with New Horizons where he is now one of our top trainers. Newton brings a thorough mentoring capability to the classroom where he can advise on technical issues and challenges often beyond the scope of the course curriculum. His combination of technical knowledge and instructor experience make him one of the most respected instructors within the IT training industry.

Read full bio
top