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 asyncTask<em>MethodName</em>() { 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.
The above is the detailed content of C# Await Async. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.
