Asynchronous Programming using C# 4.5 and Visual Studio 2011
Posted by: Mahesh Sabnis
in Category C#
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.
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 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 eBook 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 the 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!