Asynchronous Programming using async and await

What is asynchronous programming and how to write asynchronous code in C# using async and await keywords


Category: C# Tags: C#

Asynchronous Programming Code Files

Concurrency

    Concurrency means performing two or more operations at a time. When we perform multiple operations at a time we may utilize CPU to its full capacity and that’s why concurrency is powerful technique to make better performing software.

Multithreading

    Multithreading is form of concurrency which uses multiple threads to execute multiple operations at a time. Multithreading is traditional techniques to achieve concurrency but in modern programming we have parallel processing and asynchronous programming to achieve concurrency which is better than using a thread.

Parallel Processing

    Parallel processing idea comes from multithreading where multiple threads can run on multiple cores of CPU. Nowadays processors are powerful and have multiple cores to perform multiple operations simultaneously and no time slicing are required since all executes on different cores.

Asynchronous Programming

Asynchronous Programming is an another form of concurrency which avoids to create unnecessary threads to achieve concurrency. Asynchronous programming uses callbacks or futures (promise) to achieve concurrency. An asynchronous method is considered that it will be completed in future.

Asynchronous Programming
Fig 1: Asynchronous Programming

 

Asynchronous programming doesn’t block main thread and we shall see it using an example. Suppose your main thread has to read a file and for that you have a method called “Read” let’s see how is the execution flow in synchronous programming:

static void Main(string[] args)
{
    Console.WriteLine("Main Start");
    var result = Read("demofile.txt");
    Console.WriteLine("Main End");
    Console.ReadLine();

}

static string Read(string fileName)
{
    Console.WriteLine("Read Start");
    Thread.Sleep(2000);
    Console.WriteLine("Read End");
    return "Content of " + fileName;
}

Output

Main Start

Read Start

Read End

Main End

You can see "Read" method blocks the Main thread until it’s completed and line “Main Ends” prints only after “Read Ends”. Now let’s do it with Asynchronous programming:

static void Main(string[] args)
{
    Console.WriteLine("Main Start");
    var result = ReadAsync("demofile.txt");
    Console.WriteLine("Main End");
    Console.ReadLine();

}

static async Task<string> ReadAsync(string fileName)
{
    Console.WriteLine("Read Start");
    await Task.Delay(2000);
    Console.WriteLine("Read End");
    return "Content of " + fileName;
}

Output

Main Start

Read Start

Main End

Read End

You can see in asynchronous programming main thread isn’t blocked due to delay in completion of "ReadAsync" method, line “Main End” is printed before “Read End”. When execution determines await statement and result is not generated of awaited operation control comes back to main thread (or where it is called from) and start executing it, once awaited operation completes the execution goes back to "ReadAsync" and resumes execution. Let’s change our code a little and see the behavior:

static void Main(string[] args)
{
    Console.WriteLine("Main Start");
    var result = ReadAsync("demofile.txt");
    Console.WriteLine("Main Sleeps");
    Thread.Sleep(4000);
    Console.WriteLine("Main End");
    Console.ReadLine();
}

Output

Main Start

Read Start

Main Sleep

Read End

Main End

Above we put a sleep of 4 seconds in main thread, we can see line “Read End” after line “Main Sleep” because when main is in sleep awaited operation is completed and control goes back to finish "ReadAsync" method, once it is completed it comes back to main thread and completes it.

Async: async & await keywords are introduced in C# which enables asynchronous programming, any method we want to call asynchronously should be marked as async, an asynchronous method returns Task, Task<Result> or can be called a promise. A promise is something a method is expected to return on completion (in future).

Await: await keyword defines a wait for a task, until a task is completed await doesn’t let next statement to execute, it pauses the execution of async method, if result of awaited task is already produced then it executes the next statement else control goes back to caller and starts execution there. As soon awaited task is completed the control again comes back to the asynchronous method to complete the pending.

An asynchronous method should have at least one await inside else asynchronous method and synchronous method doesn’t make any difference hence asynchronous method is executed as synchronous.

Since it does not create any new thread to execute a asynchronous method it performs better than conventional multithreading techniques. For parallel processing multithreading is better option but both multithreading and asynchronous programming are different techniques but servers similar aspirations.


Like 0 People
Last modified on 6 April 2019
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 133
Questions: 9
Given Best Solutions: 9 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x