Written in front

Since the introduction of the async and await keywords in the C# 5.0 era, asynchronous programming has become popular.
Especially in the current era of .NET Core, if you don’t have async or await keywords in your code, it will make people feel very strange.

Imagine when we are dealing with UI and button clicks, we need to run a long-running method, such as reading a large file or other tasks that take a long time, in which case the entire application must wait for this The long-running task is completed to complete the entire task.

In other words, if any process in the sync application is blocked, the entire application will be blocked and our application will stop responding until the entire task is completed.

In this case, asynchronous programming will be very useful.
By using asynchronous programming, the application can continue to do other work that does not depend on the completion of the entire task.

With the help of the Async and await keywords, asynchronous programming is made simple, and we will get all the benefits of traditional asynchronous programming.

Example explanation

Suppose we use two methods, Method 1 and Method 2, which are not interdependent, and Method 1 takes a long time to complete its task.
In synchronous programming, it executes the first Method 1, and waits for the method to complete, then executes Method 2.
Therefore, this will be a time intensive process, even if the two methods are not interdependent.

We can run all methods in parallel using simple multithreaded programming, but it blocks the UI and waits for all tasks to complete.
To solve this problem, we have to write a lot of code in traditional programming, but now that we have the Async and await keywords, we will solve this problem by writing very little and concise code.

In addition, we will see more examples. If any third method (such as Method 3) relies on Method 1, it will wait for the completion of Method 1 with the help of the Wait keyword.

Async and await are code tags that mark the code location where the control should be restored after the task is completed.

Let’s take a few examples to better understand it.

Example of Async and await keywords in C#

We will use the console application for a demo.

First example

In this example, we will take two methods that are not interdependent.

class Program
{  
    static void Main(string[] args)
    {  
Method1();
Method2();
Console.ReadKey();
    }  
  
    public static async Task Method1()
    {  
await Task.Run(() =>
        {  
            for (int i = 0; i < 100; i++)
            {  
Console.WriteLine(" Method 1");  
            }  
        });  
    }  
  
  
    public static void Method2()
    {  
        for (int i = 0; i < 25; i++)
        {  
Console.WriteLine(" Method 2");  
        }  
    }  
}  

In the code given above, Method 1 and Method 2 are not dependent on each other, we are calling from the main method.

Here, we can clearly see that Method 1 and Method 2 are not waiting for the other party to complete.


Output


Detailed-usage-of-Async-and-Await-in-C1

Now let’s look at the second example, let’s say we have Method 3, which depends on Method 1

Second example

In this example, Method 1 returns the total length as an integer value. We pass a parameter in Length in Method 3, which comes from Method 1.

Here, before passing the parameters in Method 3, we must use the AWAIT keyword. To do this, we must use the async keyword in the calling method.

In the main method of the console application, the await keyword cannot be used because the async keyword cannot be used because it gives the error given below.
(But if you are using C#7.1 and above, there will be no problem, because the syntax of C#7.1 and above supports the Mian method plus async)

Detailed-usage-of-Async-and-Await-in-C2

We will create a new method as a CallMethod, in which we will call all of our methods, Method 1, Method 2, and Method 3.

class Program
{  
    static void Main(string[] args)
    {  
callMethod();
Console.ReadKey();
    }  
  
    public static async void callMethod()
    {  
Task<int> task = Method1();
Method2();
        int count = await task;
Method3(count);
    }  
  
    public static async Task<int> Method1()
    {  
        int count = 0;
await Task.Run(() =>
        {  
            for (int i = 0; i < 100; i++)
            {  
Console.WriteLine(" Method 1");  
count += 1;
            }  
        });  
        return count;
    }  
  
    public static void Method2()
    {  
        for (int i = 0; i < 25; i++)
        {  
Console.WriteLine(" Method 2");  
        }  
    }  
  
    public static void Method3(int count)
    {  
Console.WriteLine("Total count is " + count);
    }  
}  

In the code given above, Method 3 requires a parameter, the return type of Method 1.
Here, the await keyword plays a crucial role in waiting for the completion of the Method 1 task.


Output


Detailed-usage-of-Async-and-Await-in-C3

Third example

There are some support APIs in .NET Framework 4.5, and the Windows runtime includes methods that support asynchronous programming.

With the help of the Async and await keywords, we can use all of this in real-time projects to perform tasks faster.

APIs that include asynchronous methods are HttpClient, SyndicationClient, StorageFile, StreamWriter, StreamReader, XmlReader, MediaCapture, BitmapEncoder, BitmapDecoder, and so on.

In this case, we will read all the characters in the large text file asynchronously and get the total length of all the characters.

class Program
{  
    static void Main()
    {  
Task task = new Task(CallMethod);
task.Start();
task.Wait();
Console.ReadLine();
    }  
  
    static async void CallMethod()
    {  
        string filePath = "E:\\sampleFile.txt";  
Task<int> task = ReadFile(filePath);
  
Console.WriteLine(" Other Work 1");  
Console.WriteLine(" Other Work 2");  
Console.WriteLine(" Other Work 3");  
  
        int length = await task;
Console.WriteLine(" Total length: " + length);
  
Console.WriteLine(" After work 1");  
Console.WriteLine(" After work 2");  
    }  
  
    static async Task<int> ReadFile(string file)
    {  
        int length = 0;
  
Console.WriteLine(" File reading is stating");  
        using (StreamReader reader = new StreamReader(file))
        {  
            // Reads all characters from the current position to the end of the stream asynchronously   
            // and returns them as one string.   
            string s = await reader.ReadToEndAsync();
  
length = s.Length;
        }  
Console.WriteLine(" File reading is completed");  
        return length;
    }  
}  

In the code given above, we call the ReadFile method to read the contents of the text file and get the length of the total characters in the text file.

In sampleText.txt, the file contains too many characters, so it takes a long time to read all the characters.

Here, we use asynchronous programming to read everything from the file, so it won’t wait to get a return value from this method and execute other lines of code, but it must wait for the line of code given below because we are waiting For keywords, we will use the return value for the lines of code given below.

int length = await task;
Console.WriteLine(" Total length: " + length);  

Subsequently, other lines of code will be executed in order.

Console.WriteLine(" After work 1");  
Console.WriteLine(" After work 2");   


Output


Detailed-usage-of-Async-and-Await-in-C4

At last

Here, we must understand that very important, if we do not use the await keyword, then this method is used as a synchronization method.
The compiler will show us a warning but will not display any errors.

As with the simple method above, we can use the async and await keywords in C# code to happily program asynchronously.

Finally, thank you for your reading!

Reference:

https://www.c-sharpcorner.com/article/async-and-await-in-c-sharp/

https://www.cnblogs.com/yilezhu/p/10555849.html