- The async keyword is used to mark a method as an asynchronous method.
- The await keyword is used to pause the execution of an asynchronous method until a specified operation completes.
The role of "async" and "await" keywords in C# is to facilitate asynchronous programming, allowing developers to write code that can efficiently handle long-running or I/O-bound operations without blocking the main execution thread. Here's an example that illustrates their role:
csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
await DoSomethingAsync();
Console.WriteLine("Async operation completed.");
}
public static async Task DoSomethingAsync()
{
Console.WriteLine("Async operation started.");
await Task.Delay(2000); // Simulating a time-consuming task
Console.WriteLine("Async operation finished.");
}
}
In this example, the Main method is marked with the "async" keyword, indicating that it contains asynchronous operations. It then awaits the completion of the asynchronous method DoSomethingAsync()
.
The DoSomethingAsync()
method is also marked as "async" and contains an asynchronous operation simulated by the Task.Delay
method, which causes a delay of 2000 milliseconds (2 seconds). During this delay, the execution is asynchronously paused, and control is returned to the calling method, Main()
.
When the await Task.Delay(2000)
line is reached, the DoSomethingAsync()
method temporarily suspends its execution and allows the calling method, Main()
, to continue running concurrently. This ensures that the application remains responsive, and other tasks can be performed while waiting for the delay to complete.
Once the 2-second delay is over, the DoSomethingAsync()
method resumes execution after the await
statement, and the message "Async operation finished." is displayed. Finally, the execution returns to the Main()
method, and the message "Async operation completed." is printed.
By using "async" and "await", the program achieves asynchronous behavior without blocking the main thread. It allows the application to remain responsive during the delay and enables the execution of other tasks while waiting for the asynchronous operation to complete.