Async And Await In C#

Nowadays, Asynchronous programming is very popular with the help of the async and await keywords in C#.

When we are dealing with UI and on button click, we use a long running method like reading a large file or something else which will take a long time, in that case, the entire application must wait to complete the whole task.

In other words, if any process is blocked in a synchronous application, the entire application gets blocked and our application stops responding until the whole task completes.

Asynchronous programming is very helpful in this condition. By using Asynchronous programming, the Application can continue with the other work that does not depend on the completion of the whole task.

We will get all the benefits of traditional Asynchronous programming with much less effort by the help of async and await keywords.

Suppose, we are using two methods as Method1 and Method2 respectively and both the methods are not dependent on each other and Method1 is taking a long time to complete its task. In Synchronous programming, it will execute the first Method1 and it will wait for completion of this method and then it will execute Method2. Thus, it will be a time intensive process even though both the methods are not depending on each other.

We can run all the methods parallelly by using the simple thread programming but it will block UI and wait to complete all the tasks. To come out of this problem, we have to write too many codes in traditional programming but if we will simply use the async and await keywords, then we will get the solutions in much less code.

Also, we are going to see more examples, if any third Method as Method3 has a dependency of method1, then it will wait for the completion of Method1 with the help of await keyword.

Async and await are the code markers, which marks code positions from where the control should resume after a task completes.

Let’s start with practical examples for understanding the programming concept.

Sample examples of async and await keyword in C#

We are going to take a console Application for our demonstration.

Example 1

In this example, we are going to take two methods, which are not dependent on each other.

Code sample

  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             Method1();
  6.             Method2();
  7.             Console.ReadKey();
  8.         }
  9.         public static async Task Method1()
  10.         {
  11.             await Task.Run(() =>
  12.             {
  13.                 for (int i = 0; i < 100; i++)
  14.                 {
  15.                     Console.WriteLine(” Method 1″);
  16.                 }
  17.             });
  18.         }
  19. public static void Method2()
  20.         {
  21.             for (int i = 0; i < 25; i++)
  22.             {
  23.                 Console.WriteLine(” Method 2″);
  24.             }
  25.         }
  26. }

In the code given above, Method1 and Method2 are not dependent on each other and we are calling from the Main method.

Here, we can clearly see Method1 and Method2 are not waiting for each other.

Now, coming to the second example, suppose we have Method3, which is dependent on Method1

Example 2

In this example, Method1 is returning total length as an integer value and we are passing a parameter as a length in a Method3, which is coming from Method1.

Here, we have to use await keyword before passing a parameter in Method3 and for it, we have to use the async keyword from the calling method.

We can not use await keyword without async and we cannot use async keyword in the Main method for the console Application because it will give the error given below.

We are going to create a new method as callMethod and in this method, we are going to call our all Methods as Method1, Method2 and Method3 respectively.

Code sample

  1. class Program
  2. s    {
  3.         static void Main(string[] args)
  4.         {
  5.             callMethod();
  6.             Console.ReadKey();
  7.         }
  8.         public static async void callMethod()
  9.         {
  10.             Task<int> task = Method1();
  11.             Method2();
  12.             int count = await task;
  13.             Method3(count);
  14.         }
  15.         public static async Task<int> Method1()
  16.         {
  17.             int count = 0;
  18.             await Task.Run(() =>
  19.             {
  20.                 for (int i = 0; i < 100; i++)
  21.                 {
  22.                     Console.WriteLine(” Method 1″);
  23.                     count += 1;
  24.                 }
  25.             });
  26.             return count;
  27.         }
  28.        public static void Method2()
  29.         {
  30.             for (int i = 0; i < 25; i++)
  31.             {
  32.                 Console.WriteLine(” Method 2″);
  33.             }
  34.         }
  35.         public static void Method3(int count)
  36.         {
  37.             Console.WriteLine(“Total count is “ + count);
  38.         }
  39. }

In the code given above, Method3 requires one parameter, which is the return type of Method1. Here, await keyword is playing a vital role for waiting of Method1 task completion.

Real time example

There are some supporting API’s from the .NET Framework 4.5 and the Windows runtime contains methods that support async programming.

We can use all of these in the real time project with the help of async and await keyword for the faster execution of the task.

Some APIs that contain async methods are HttpClient, SyndicationClient, StorageFile, StreamWriter, StreamReader, XmlReader, MediaCapture, BitmapEncoder, BitmapDecoder etc.

In this example, we are going to read all the characters from a large text file asynchronously and get the total length of all the characters.

Sample code

  1. class Program
  2.     {
  3.         static void Main()
  4.         {
  5.             Task task = new Task(CallMethod);
  6.             task.Start();
  7.             task.Wait();
  8.             Console.ReadLine();
  9.         }
  10.         static async void CallMethod()
  11.         {
  12.             string filePath = “E:\\sampleFile.txt”;
  13.             Task<int> task = ReadFile(filePath);
  14.             Console.WriteLine(” Other Work 1″);
  15.             Console.WriteLine(” Other Work 2″);
  16.             Console.WriteLine(” Other Work 3″);
  17.             int length = await task;
  18.             Console.WriteLine(” Total length: “ + length);
  19.             Console.WriteLine(” After work 1″);
  20.             Console.WriteLine(” After work 2″);
  21.         }
  22.         static async Task<int> ReadFile(string file)
  23.         {
  24.             int length = 0;
  25.             Console.WriteLine(” File reading is stating”);
  26.             using (StreamReader reader = new StreamReader(file))
  27.             {
  28.                 // Reads all characters from the current position to the end of the stream asynchronously
  29.                 // and returns them as one string.
  30.                 string s = await reader.ReadToEndAsync();
  31.                 length = s.Length;
  32.             }
  33.             Console.WriteLine(” File reading is completed”);
  34.             return length;
  35.         }
  36. }

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

In our sampleText.txt, file contains too many characters, so It will take a long time to read all the characters.

Here, we are using async programming to read all the contents from the file, so it will not wait to get a return value from this method and execute the other lines of code but it has to wait for the line of code given below because we are using await keyword and we are going to use the return value for the line of code given below..

  1. int length = await task;
  2.             Console.WriteLine(” Total length: “ + length);

Subsequently, other lines of code will be executed sequentially.

  1. Console.WriteLine(” After work 1″);
  2.             Console.WriteLine(” After work 2″);

Output

Here, we have to understand very important points that if we are not using await keyword, then the method works as a synchronous method. The compiler will show the warning to us but it will not show any error.

In this easy way, we can use async and await keywords for Asynchronous programming in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *