Asynchronous Programming using Async and Await - C#

Why do we go for Asynchronous Programming?

when the application performs a lengthy operation using the UI thread, which in turn isn't available to take care of the UI until the operation ends. To provide a responsive UI experience, potentially lengthy operations should be done asynchronously, on a separate thread we go for Asynchronous Programming

Async and Await in C#

.NET 4.5 / C# 5 made ease of writing asynchronous programming by introducing async and await. Using async and await in C#, you can write write asynchronous code as simple as synchronous code.

public async string ReadContent()
{
    var httpClient = new HttpClient();
    var contentString = await httpClient.GetStringAsync("http://www.programmersguide.net");
    return contentString;
}

The above code connects to programmersguide.net and retrieves the contents. The performance of this process is also relies on the speed of the internet. So the synchronous code will keep the UI thread busy as it got hooked with the process of retrieving the string from the website. But, this can be avoided by asynchronous code with the help of the magic words async and await

the method is decorated with the async keyword, the call to retrieve the content is preceded by await, and the method that is called to perform is GetStringAsync, which is the asynchronous counterpart of the GetString method.

The async keyword decorates the method and tells the compiler that this method may contain the await keyword. The await keyword is probably the most interesting change we introduced to the code. Once we start the download operation asynchronously by calling the appropriate method, we want to release the UI thread until the download is complete. The await keyword does exactly that. Whenever our code encounters an await, the method actually returns. Once the awaited operation completes, the method resumes. That is, it continues executing from where it stopped.