Introduction to the Asynchronous Programming in C# 5.0

No.of Views1849
Bookmarked0 times
Downloads 
Votes0
By  abhi2434   On  26 Nov 2010 07:11:12
Tag : CSharp , General
Before the introduction of these features, we generally rely on traditional approaches of creating Thread from a ThreadPool and consuming a method which needed to be asynchronously called for. Again when the Thread finishes, or during the lifetime of the Thread we need callbacks to notify UI after a while, so that the user gets an impression that the background is updating the system
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

I was not aware of what Microsoft is thinking about it. But today after I saw PDC 2010 the main concern that Microsoft is pointing to on the release of C# 5.0 is the pain related to deal with asynchronous operations using Threads. It simplifies the existing MultiThreading model with Task based model, which now simplified with greater extent with the use of two new keywords yet not introduced as "await" and "async".

The History

Before the introduction of these features, we generally rely on traditional approaches of creating Thread from a ThreadPool and consuming a method which needed to be asynchronously called for. Again when the Thread finishes, or during the lifetime of the Thread we need callbacks to notify UI after a while, so that the user gets an impression that the background is updating the system. This breaks the way we write or the way we think of programming. The programmer needs to create the program to device in such a way that it handles continuity of the application by writing custom callbacks to the system or even use Dispatcher to update the UI thread from background. Thus the code becomes more and more complex as we add up more functionalities to the system.

The Present

In this PDC, Anders Hejlsberg introduces two new investments on C# which is probably now still in CTP to allow asynchronous calls to the applications very simple and easy to handle. The two keyword which were introduced recently are "async" and "await". Let me introduce these two keywords for the time being.

What is await ?

According to Whitepaper published on the CTP, await keyword lets you to wait your program and lets the program to be declared as a continuation of all the existing awaits so that the compiler automatically waits for all other awaits to be finished until the program continues its execution.

In other words, say you have invoked 3 asynchronous methods from your code an asynchronous block from your code, you would just write the way you would have written this synchronously with a single keyword await before the call. The call lets the compiler wait until the execution successfully completes. Just as shown below :

async Task GetStringsFromUrlAsync(string url)
{
     WebClient client = new WebClient();return await client.DownloadStringTaskAsync(new Uri(url));
}

This involves the call to DownloadStringTaskAsync which is already implemented for WebClient. Now as you can see I have specified the await just before the call to Asyncrhonous method DownloadStringTaskAsync, it will keep the call on wait.

Even though if I say use :

async Task GetStringsFromUrlAsync(string url)
 {
      WebClient client = new WebClient();
      Task<string> modifieduri = client.DownloadStringTaskAsync(new Uri(url));string result = await modifieduri;return await client.DownloadStringTaskAsync(new Uri(result));
}

It means the second Task depends on the first one. So in this case the First DownloadStringTaskAsync will be called. This call actually returns Task(Task for any other operation) which you can keep on wait until it is finished using await keyword. So when you execute, the first call will block until the result is fetched and then it will take the string result and call the next one.

Thus you can see how you can use await on Task variable to wait the object for completion without any implementation of custom callbacks, global objects etc.

What is async?

Now how to implement the asynchronous method? Hmm, async keyword can be placed just before the function call to make the method asynchronous.

By specifying the async keyword against your method call, the compiler will automatically select your method to be asynchronous, which means it will move to the next line before returning the result in parallel until it finds an await. In the example I have provided the DownloadStringTaskAsync is actually an extension which specifies to be called with async.

Async method can return void, Task or Task based on what you need in your environment. But it is mostly preferable to  return at least a Task object so that the caller can better handle the call.

For any async method, you should put await before fetching the result, otherwise you might end up with blank/null result. await works with async to stop the further execution before finishing the other operations in context.

How to Try ?

You can download and read more about it from :http://msdn.microsoft.com/en-us/vstudio/async.aspx

Conclusion

I have composed this article just to give you an introduction on what I understood about the concept on the PDC discussed today. My understanding might be totally wrong as I don't have much depth about the concept. Please let me know if I made any mistake so that I can correct it in this article. This is the very basic introduction to these new concepts,  I will introduce few more extension methods and other important features that were also included with the CTP later on.

 
Sign Up to vote for this article
 
About Author
 
abhi2434
Occupation-Not Provided
Company-Not Provided
Member Type-Senior
Location-Not Provided
Joined date-22 Oct 2009
Home Page-Not Provided
Blog Page-Not Provided
 
 
Other popularSectionarticles
    Are you somewhat confused between Serialization and Marshaling? This writing would break this confusion up, it would give you a basic understanding of the process of Serialization and the process of Marshaling, and how you can get the most out of each.
    Published Date : 10/May/2010
    First, this writing concentrates of and compares between three programming languages, C#, C++/CLI, and ISO/ANSI C++. It discusses 9 rules that every developer should keep in mind while working with constructors, destructors, and finalizers and class hierarchies:
    Published Date : 05/May/2010
    This article explains how to filter rows in a DataSet/DataTable. The example provided will help you get information faster.
    Published Date : 23/May/2010
    In this article, I will explain three basic terms of C#, such as Call Stack ,Call Site and stack Unwinding
    Published Date : 17/Aug/2010
    In this article, I will discuss about Checked and unchecked keyword and conversions in C#.
    Published Date : 16/Aug/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top