How to write async method using Task parallel library in C# 4.0?

+1 vote
asked Jun 12, 2013 in C#.NET by anonymous

How to use async and await keywords to create asynchronous method in C# 4.5? How does it work? Will it increase the performance or it is for some different purpose? What is the concept behind these two keywords


1 Answer

+1 vote
answered Jun 13, 2013 by administrator (315 points)
selected Jun 21, 2013 by Aadhira
Best answer

Microsoft has done a wonderful job for creating asynchronous methods in a very easy way and very easy to follow what is going on. No longer we need to block the thread until it completes.No need write multiple lines of code to create asynchronous programming and no need to scratch the head to understand what is going on.

Dot net framework 4.5 has come up with two new keywords which makes the life very easy to create asynchronous methods anywhere.

async and await

async keyword will make the method to run asynchronous. "await" will make sure to suspend the async method and release the calling thread.

Without using await keyword in the async method, the method will be executed synchronous. Even though await is making the method to run asynchronous, "await" keyword can be used only inside a method which are declared async.

So, when the call reach the code "await", it will suspend the code at that place and release the current thread. Task parallel library will do the things in behind to execute method which was called using await keyword, and pass the control back to the same line once the asynchronous call is done.

Below sample code may help to understand better.

using System;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncDemo
    class Program
        static void Main(string[] args)
            LongRunAsync longRun = new LongRunAsync();
            var task = longRun.LongRunningMainAsync();
           Console.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " back to main method and waiting for all task to complete");

            Console.WriteLine("All tasks completed");

    public class LongRunAsync
        public async Task LongRunningMainAsync()
            Console.WriteLine("LongRunningMainAsync started at thread: " + Thread.CurrentThread.ManagedThreadId);
            await Task.Delay(2000);
            Task task1 = LongRunningTask1Async();
            Task task2 = LongRunningTask2Async();

            await Task.WhenAll(task1, task2);
            Console.WriteLine("LongRunningMainAsync completed at thread: " + Thread.CurrentThread.ManagedThreadId);

        public async Task LongRunningTask1Async()
            Console.WriteLine("LongRunningTask1Async started at thread: " + Thread.CurrentThread.ManagedThreadId);
            await Task.Delay(2000);
            Console.WriteLine("LongRunningTask1Async completed at thread: " + Thread.CurrentThread.ManagedThreadId);
        public async Task LongRunningTask2Async()
            Console.WriteLine("LongRunningTask2Async started at thread: " + Thread.CurrentThread.ManagedThreadId);
            await Task.Delay(2000);
            Console.WriteLine("LongRunningTask2Async completed at thread: " + Thread.CurrentThread.ManagedThreadId);

In the above code, all methods in "LongRunAsync" declared with "async" keyword. That means, we can use "await" keyword inside those methods.

Since the main method in class "Program" is not having async keyword, I could not use "await" keyword on the main method to call "LongRunningMainAsync" method in "LongRunAsync" class. Instead, I used "Task" class to start the long running method and waited using task.wait(). If I have not used task.wait, then my main method may not wait for any other task to complete when it get the thread. It will complete the execution.

Next, instead of Thread.Sleep(2000), I have used await Task.Delay(2000); both or going to delay 2 seconds. But when there is a await keyword sleep will be called asynchronous. So, once sleep called the calling thread will be release to main method.

The same thing going to happen whenever the runtime see "await" keyword.

Below is the result of the program
LongRunningMainAsync started at thread: 8
Thread 8 back to main method and waiting for all task to complete
LongRunningTask1Async started at thread: 10
LongRunningTask2Async started at thread: 10
LongRunningTask1Async completed at thread: 11
LongRunningTask2Async completed at thread: 10
LongRunningMainAsync completed at thread: 10
All tasks completed

async and await is used increase the performance, also it releases unused threads to the thread pool to take the next task which makes multiple task to run parallel in a multi core machine.

Your answer


Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015