In this article I will discuss about the async await keywords. These have been introduces in the C# 5.0 and .NET 4.5 framework to make task parallel library more convenient to use with tasks. Many times while working on the long running operation we stumble upon usage of asynchronous programming. Here we want to use C#’s async and await keyword but don’t know how to use it with C#. In this article I will use the same example which I have used in my previous article about C# task result, continuation and exception. You can read about the basic of task here.
async await Usage Code Example in C#
As I have already mentioned that I will be using the code from my previous article. I am downloading the HTML page as string for locally hosted MVC project. Since this operation of the sending the request and downloading the string at the client is a time consuming operation we can assume it be any long running operation in C# programming.
Before going any further let’s dive into the code for async await in C#.
static Stopwatch stopWatch = new Stopwatch(); static void Main(string[] args) { Console.WriteLine("Issue the request"); DownloadStringAsyncAwait(); Console.WriteLine("Time taken to complete request:" + stopWatch.ElapsedMilliseconds); Console.Read(); } public async static void DownloadStringAsyncAwait() { Tasktask = NewMethod(); DoIndependentWork(); await task; if (task.IsCompleted) Console.WriteLine(task.Result); } private static void DoIndependentWork() { Console.WriteLine("Working independently"); } private static Task NewMethod() { return Task .Factory.StartNew(() => { WebClient webCleint = new WebClient(); string siteContent = webCleint.DownloadString("http://localhost:57196/Home"); webCleint.Dispose(); return siteContent; }); }
The result of the above code is shown in the below figure:
Figure 1
As seen in the above code for the DownloadStringAsyncAwait() method we can notice that async and await keywords have helped us to write a totally asynchronous method in a synchronous structure and simplicity.
The async modifier tell to the compiler to treat a await as a keyword. Async can only be applied to the methods which return type void, Task or Task
Methods with async modifiers are called asynchronous methods as generally they are asynchronous in nature. To understand this concept lets check the above code and figure.
As stated previously DownloadStringAsyncAwait() is the asynchronous method which is using a different thread to perform some long running operation(to download HTML in this case).
async await keyword is a syntactic sugar for the Task and Continuation as shown in the below code snippet. Here we are doing the same operation but without async await.
public static void DownloadStringAsyncAwait() { Tasktask = NewMethod(); DoIndependentWork(); task.ContinueWith(t => { if (task.IsCompleted) Console.WriteLine(task.Result); }); }
As seen in the figure 1 above just after issuing the request I called a method which DoIndependentWork() which executes on the main thread. It starts as soon as request is sent to work on Thread pool thread.
And after creating a task, the control is returned to the Main() method which shows it takes only 14 milliseconds to do all this process, but NewMethod() is still busy with its operation to get the HTML from the requested URL.
And once NewMethod() is done with its operation the control returns to the await keyword in the DownloadStringAsyncAwait() method. Here it resumes the operation just after the await keyword, in this case writing the result to the console.
If this were a UI application it would be responsive even for the long running operation.
Conclusion:
In this article we have seen how we can use async await keywords in C# to carry on long running operation asynchronously. We also seen how we can use the await keyword to carry on the remaining part of the operation.
Buck Davies says
This was extremely helpful for basic understanding of async / await. Thank you.