Your Ultimate async / await Tutorial in C#

AramT
6,215 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

There are some libraries in .Net Framework 4.5, that has a built-in support for asynchronous programming using asyncawait keywords.

These libraries, such as the HttpClient, StreamWriter, StreamReader and many more, provide you async methods that you can use in your program directly with await.

They have been added with the async/await capabilities because these provide functionalities that require long-running operations such as reading large file or download huge resources.

So the asyncawait will significantly improve the performance of your application while not blocking the UI or the execution.

I/O Bound async / await

Let's take an example for using the HttpClient's GetStringAsync method, that will hit a provided URL and return the html response content from it and display its length on Console screen:

Click run to see the console output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
·using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace AsyncApp
{
class Program
{
private const string URL = "https://docs.microsoft.com/en-us/dotnet/csharp/csharp";
static void Main(string[] args)
{
DoSynchronousWork();
var someTask = DoSomethingAsync();
DoSynchronousWorkAfterAwait();
someTask.Wait(); //this is a blocking call, use it only on Main method
Console.ReadLine();
}
public static void DoSynchronousWork()
{
// You can do whatever work is needed here
Console.WriteLine("1. Doing some work synchronously");
}
static async Task DoSomethingAsync() //A Task return type will eventually yield a void
{
Console.WriteLine("2. Async task has started...");
await GetStringAsync(); // we are awaiting the Async Method GetStringAsync
}
static async Task GetStringAsync()
{
using (var httpClient = new HttpClient())
{
Console.WriteLine("3. Awaiting the result of GetStringAsync of Http Client...");
string result = await httpClient.GetStringAsync(URL); //execution pauses here while awaiting GetStringAsync to complete
//From this line and below, the execution will resume once the above awaitable is done
//using await keyword, it will do the magic of unwrapping the Task<string> into string (result variable)
Console.WriteLine("4. The awaited task has completed. Let's get the content length...");
Console.WriteLine($"5. The length of http Get for {URL}");
Console.WriteLine($"6. {result.Length} character");
}
}
static void DoSynchronousWorkAfterAwait()
{
//This is the work we can do while waiting for the awaited Async Task to complete
Console.WriteLine("7. While waiting for the async task to finish, we can do some unrelated work...");
for (var i = 0; i <= 5; i++)
{
for (var j = i; j <= 5; j++)
{
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content