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
·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