Asynchronous Programming using C# 4.5 and Visual Studio 2011

Posted by: Mahesh Sabnis , on 4/6/2012, in Category C#
Views: 146610
Abstract: The new keywords async and await introduced in C# 4.5 helps developers to make their asynchronous programming logic less complex and more manageable. In this article, we will see a simple demonstration of the async programming in C# 4.5

Note: This article is based on .NET 4.5 Beta and VS 2011 Beta and is subject to change

As a developer, I often do File Operations like writing and reading to and from a file, performing file Uploads and Downloads to and from a file server and so on. In such scenarios, if the size of the file is huge and if number of files to be uploaded and downloaded are more than what can be managed by the application, I go in for Asynchronous programming using BeginInvoke() method of the delegate. In this case, it is necessary for me to implement complex threading mechanisms which can at times make my code complex and a difficult to maintain.

However when I came across the new features in.NET Framework 4.5 and C# 4.5, I found a simple solution. The developer community has been provided with a new simplified approach for Asynchronous programming which can make a developer’s life simpler. Following are the new Keywords introduced:

async: This modifier indicates the method is now asynchronous. The benefit of using this keyword is that it provides a simpler way to perform potentially long-running operations without blocking the callers thread. The caller of this async method can resume its work without waiting for this asynchronous method to finish its job. This reduces developer’s efforts for writing an additional code. The method with async modifier has at least one await. This method now runs synchronously until the first await expression written in it.

await: Typically, when a developer writes some code to perform an asynchronous operations using threads, then he/she has to explicitly write necessary code to perform wait operations to complete a task. In asynchronous methods, every operation which is getting performed is called a Task. Here the task is also known as an ongoing work or work to perform.

The ‘await’ keyword is applied on the task in an asynchronous method and suspends the execution of the method, until the awaited task is not completed. During this time, the control is returned back to the caller of this asynchronous method.

You must keep in mind that the keyword ‘async’ is applied on the method which is decorated with the ‘async’ keyword. The most important behavior of the await keyword is it does not block the thread on which it is executing. What it does it that it signals to the compiler to continue with other async methods, till the task is in an await state. Once the task is completed, it resumes back where it left off from.

In the example shown below, I have demonstrated a simple File operations using the Stream class in the System.IO namespace. The targeting framework is .NET 4.5. The prerequisites for this example are Visual Studio 2011 beta, which you can download here.

Step 1: Open VS2011 (beta), and create a new console application, name it as ‘CS_FileReader_Sync_Async’. Make sure that the .NET 4.5 is selected. In the Debug folder, add a new docx file and name it as ‘MyFile.docx’.


Step 2: Add the following code in Program.cs



If you carefully go through the code, you will find that ‘OpenReadWriteFile()’ method performs a traditional operation for Reading and Writing file. The method ‘Print()’ is just a helper method, the reason behind introducing this method that in the async method, when an await expression is read, the control will be sent back to the Caller and the execution takes place. So here the ‘Print()’ method gets executed when the first await expression in the ‘OpenReadWriteFileAsync()’ asynchronous method is read. In the ‘Main()’ method, first the synchronous ‘OpenReadWriteFile()’ method is called followed by ‘OpenReadWriteFileAsync()’ asynchronous method and then ‘Print()’ method.

Step 3: Run the application and the result will be similar to the one shown below:


Conclusion: The new keywords async and await introduced in C# 4.5 helps developers to make their asynchronous programming logic less complex and more manageable.

The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by sachin nimbalkar on Friday, April 6, 2012 11:59 PM
New features in .NET Framework 4.5 and C# 4.5 are really good for Coders.
Comment posted by Gaurav Pandey on Saturday, May 5, 2012 4:17 PM
Quite useful article. I think few lines of code have been repeated in OperationReadWrieAsync func.
Comment posted by Jalpesh Vadgama on Tuesday, May 29, 2012 5:19 AM
nice work

Comment posted by amitkpatel on Monday, July 16, 2012 8:54 AM
Good One
Comment posted by Sunil on Wednesday, August 22, 2012 7:32 AM
Hi Mahesh

That is good artical could you please explain more about What does the “await” & Async keyword do?


Comment posted by Deepak Kataria on Friday, August 2, 2013 6:14 AM
Hi Mahesh,

Nice Work,

Is Microsoft launch Visual Studio 2011 ?

as my thought Visual Studio 2012 and Now Visual Studio 2013...

If i wrong then pls correct me?

Deepak Kataria
DotNet Developer (MVC)
Comment posted by Suprotim Agarwal on Friday, August 2, 2013 12:15 PM
@Deepak: Visual Studio 2011 was a preview release. The final release was called VS 2012.
Comment posted by Deepak Kataria on Sunday, August 4, 2013 10:48 PM
Daer Suprotim Agarwal,

Thanks for the Information.

Comment posted by Noixes on Wednesday, April 30, 2014 5:19 AM
in your async method, you write "In Read Operation Async" in your console twice but you only show it once in your console.
why ?
Comment posted by tarran on Friday, January 30, 2015 8:23 AM
nice article