Updated April 20, 2023
Introduction of C# Await Async
In C#, async and await keywords are used in asynchronous programming. Sometimes in our application, the UI gets blocked because of some process such as a long method running in our application. UI becomes responsive when this process ends.
If we want our application to be responsive irrespective of any process running in the background, then we can make use of async and await keyword which will make our code asynchronous which in result allows our application to start executing other code when already a long method is executing which is independent of other code.
Syntax:
public asyncTaskMethodName()
{
await Task.Run(
//user code
);
}
In the above statements, async and await keywords specify that this code is asynchronous code. The method ‘MethodName’will execute asynchronously and it will execute the code inside Task.Run() without blocking the application.
How does Await and Async Work in C#?
In sequential and synchronous programming, the code will not execute further i.e. the next statement will not get executed until and unless the current statement finishes working. Such type of execution takes more time for long calculations and can sometimes make our application irresponsive. To overcome such a situation, we can make our code asynchronous with the help of async and await keyword.
For example, if we have two methods in our code and these methods are independent of each other. The first method is doing a long calculation and the second method is printing some details of the application. The first method requires more time to execute than the second method. If our code is synchronous then the second method will not be executed until and unless the first method completes its execution.
On the other hand, if we have used async and await keywords in our first method to make it asynchronous then the second method can start its execution irrespective of the completion of the first method. This asynchronous programming takes less time to execute and thus makes our application more responsive and user friendly in nature.
Any method using the await keyword must be marked as async. The async keyword is used in the method signature which tells the compiler that this method is an asynchronous method. We can also apply async to the overloaded method. Writing asynchronous code using async and await does not mean that our task will be performed by multiple threads but it ensures that the main thread of the application will not be blocked. We cannot use async without await and also we cannot use await without async. We can use these keywords to write asynchronous code to perform both IO bound and CPU bound operations.
In an asynchronous method, the await operator hangs the processing of that method until its operand finishes executing the corresponding asynchronous operation. After the completion of the asynchronous operation, the await operator returns the result of this asynchronous operation. On the other hand, if the operand of the await operator has already completed its operation then the await operator does not suspend the processing of the corresponding asynchronous method and immediately returns the result of the operation without any suspension of the async method. On suspension of the async method by the await operator, the control from that asynchronous method returns back to the caller method.
Please find below some points to keep in mind while working with async and await keywords:
- If a method is marked as async then there should be a use of await operator inside this method otherwise the user will get a warning from the compiler and the method will get executed like any other normal method.
- The ‘async void’ should be used only for event handlers and not for methods because the event does not have any return type.
- The exceptions thrown by the method marked as ‘async void’ cannot be caught outside the method and also it is very difficult to test such a method.
Examples of C# Await Async
Following are the examples are given below:
Example #1
Code:
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp4
{
public class Program
{
public static void Main()
{
TaskMethod();
Console.ReadLine();
}
public static async void TaskMethod()
{
Task<int> task = new Task<int>(CountCharacters);
task.Start();
Console.WriteLine("1. Other task executing");
Console.WriteLine("2. Other task executing");
Console.WriteLine("3. Other task executing");
int count = await task;
Console.WriteLine(" Total characters in file: " + count);
Console.WriteLine("1. After executing task");
Console.WriteLine("2. After executing task");
}
//method to count number of characters in file
public static intCountCharacters()
{
int count = 0;
string filePath = @"E:\Content\content.txt";
Console.WriteLine("Reading file");
using (StreamReaderstreamReader = new StreamReader(filePath))
{
//reading the whole content of the file
string fileContent = streamReader.ReadToEnd();
count = fileContent.Length;
}
Console.WriteLine("File reading completed");
return count;
}
}
}
Output:
We can see in the output that the above program executed asynchronously. The process of file reading started and while the file is being read, the statements after the file reading process started executing without waiting for the file to be read completely.
Example #2
Please find below another example of async and await to calculate the sum of numbers till 1000.
Code:
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp4
{
public class Program
{
public static void Main()
{
TaskMethod();
Console.ReadLine();
}
public static async void TaskMethod()
{
Task<int> task = new Task<int>(AddNumbers);
task.Start();
Console.WriteLine("1. Other task executing");
Console.WriteLine("2. Other task executing");
Console.WriteLine("3. Other task executing");
int total = await task;
Console.WriteLine(" Sum of numbers till 1000: " + total);
Console.WriteLine("1. After executing task");
Console.WriteLine("2. After executing task");
}
//method to add numbers from 1 to 1000
public static intAddNumbers()
{
int count = 0;
Console.WriteLine("Adding numbers");
for (inti = 0; i<= 1000; i++)
{
count += i;
}
return count;
}
}
}
Output:
Conclusion
The async and await keywords in C# is used to write asynchronous code. If a method is performing a long calculation or if there is an operation that requires more time to execute then we can do these operations asynchronously due to which our application will be responsive.
Recommended Articles
This is a guide to C# Await Async. Here we also discuss the introduction and how does await and async work in c#? along with different examples and its code implementation. You may also have a look at the following articles to learn more –