Async and Await are the two keywords that help us to program asynchronously. An async keyword is a method that performs asynchronous tasks such as fetching data from a database, reading a file, etc, they can be marked as "async". Whereas await keyword making "await" to a statement means suspending the execution of the async method it is residing in until the asynchronous task completes. After suspension, the control goes back to the caller method. Once the task completes, the control comes back to the states where await is mentioned and executes the remaining statements in the enclosing method.
Let us see the behavior of the code with and without async and await operators.
Synchronous Programming:
In general, the code executes sequentially i.e statements are executed one after the other. Let us take a small example of a school that has classes 11 and 12.
- The first thing school does is start the assembly which might be having morning prayer, pledge, daily updates, etc
- After the assembly, teachings begin for class 11 & class 12.
In our synchronous code below, we will be using the Stopwatch to record the execution time taken by the code. We have three methods in which Thread.Sleep(n) is specified to simulate that these methods take some time to run.
Example 1:
C#
// C# program
using System;
using System.Threading;
public class GFG{
static void Main(string[] args)
{
Demo();
Console.ReadLine();
}
public static void Demo() {
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
StartSchoolAssembly();
TeachClass12();
TeachClass11();
watch.Stop();
Console.WriteLine($"Execution Time:
{watch.ElapsedMilliseconds} ms");
}
public static void StartSchoolAssembly()
{
Thread.Sleep(8000);
Console.WriteLine("School Started");
}
public static void TeachClass12()
{
Thread.Sleep(3000);
Console.WriteLine("Taught class 12");
}
public static void TeachClass11()
{
Thread.Sleep(2000);
Console.WriteLine("Taught class 11");
}
}
Output:
Asynchronous Programming:
Using asynchronous programming indicates that a method can execute without waiting for another method to complete. Using async and await, we can run the methods above parallelly.
Example 2:
C#
// C# program for async and await
using System;
using System.Threading;
using System.Threading.Tasks;
public class GFG{
static void Main(string[] args)
{
Demo();
Console.ReadLine();
}
public static void Demo() {
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
var task1 = StartSchoolAssembly();
var task2 = TeachClass12();
var task3 = TeachClass11();
Task.WaitAll(task1, task2, task3);
watch.Stop();
Console.WriteLine($"Execution Time:
{watch.ElapsedMilliseconds} ms");
}
public static async Task StartSchoolAssembly()
{
await Task.Run(() =>
{
Thread.Sleep(8000);
Console.WriteLine("School Started");
});
}
public static async Task TeachClass12()
{
await Task.Run(() =>
{
Thread.Sleep(3000);
Console.WriteLine("Taught class 12");
});
}
public static async Task TeachClass11()
{
await Task.Run(() =>
{
Thread.Sleep(2000);
Console.WriteLine("Taught class 11");
});
}
}
Output:
Notice that these methods above have run parallelly and the execution time taken will be the same as the time taken by StartSchoolAssembly() as this is the method that is taking the longest time.
Do we really want this output? How can we start teaching classes 11 and 12 without starting the school assembly? Let us wait for the school assembly to finish irrespective of how long it is taking and later the teaching for classes 11 and 12 can begin.
Here task1 represents the school assembly. Therefore let us use the await keyword to wait for the school assembly task to finish.
Example 3:
C#
// C# program for await keyword
using System;
using System.Threading;
using System.Threading.Tasks;
public class GFG
{
static void Main(string[] args)
{
Demo();
Console.ReadLine();
}
public static async void Demo()
{
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
var task1 = StartSchoolAssembly();
await task1;
var task2 = TeachClass12();
var task3 = TeachClass11();
Task.WaitAll(task1, task2, task3);
watch.Stop();
Console.WriteLine($"Execution Time:
{watch.ElapsedMilliseconds} ms");
}
public static async Task StartSchoolAssembly()
{
await Task.Run(() =>
{
Thread.Sleep(8000);
Console.WriteLine("School Started");
});
}
public static async Task TeachClass12()
{
await Task.Run(() =>
{
Thread.Sleep(3000);
Console.WriteLine("Taught class 12");
});
}
public static async Task TeachClass11()
{
await Task.Run(() =>
{
Thread.Sleep(2000);
Console.WriteLine("Taught class 11");
});
}
}
Output:
Notice that the TeachClass12() and TeachClass11() execute only after the StartSchoolAssembly() completes. The school assembly takes 8 seconds to complete. Class 11 finishes the class soon as it takes only 2 seconds. Class 12 finishes a bit late as it takes 3 seconds. Therefore the total execution time is 8s + 3s = 11s.
Similar Reads
How to create a Queue in C#
Queue() Constructor is used to initializes a new instance of the Queue class which will be empty, and will have the default initial capacity, and uses the default growth factor. Queue represents a first-in, first out collection of object. It is used when you need first-in, first-out access of items.
2 min read
C# ReaderWriterLockSlim Class
In C#, the ReaderWriterLockSlim class is present in the System.Threading namespace which is used to provide synchronization in a multithreaded environment. It allows multiple threads to read the resource concurrently, but only one thread can write at a time Key Features: More flexibility and optimiz
8 min read
Anonymous Method in C#
An anonymous method is a method which doesnât contain any name which is introduced in C# 2.0. It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods. An Anonymous method is defined using the delegate keyword and the use
3 min read
What is Anonymous Types in C#?
Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer. Or in other words, an anonymous type prov
5 min read
C# Lifecycle and States of a Thread
In C#, threads enable the concurrent execution of tasks, it improves application performance and responsiveness. Understanding the lifecycle and states of a thread is essential for managing and synchronizing threads efficiently. A thread in C# can exist in one of the following states at any given ti
4 min read
Stack.IsSynchronized Property in C#
This method(comes under System.Collections namespace) is used to get a value indicating whether access to the Stack is synchronized (thread safe) or not. To guarantee the thread safety of the Stack, all operations must be done through the wrapper returned by the Synchronized method. Also, retrieving
2 min read
How to Terminate a Thread in C#?
In C#, threads are used to achieve tasks concurrently, a fundamental feature in multithreading and parallel programming. However, there are scenarios where we need to terminate a thread. There are different ways to terminate a thread and in this article, we will discuss those ways with their code im
6 min read
Stack.Synchronized() Method in C#
This method(comes under System.Collections Namespace) is used to return a synchronized (thread safe) wrapper for the Stack. To guarantee the thread safety of the Stack, all operations must be done through this wrapper. Syntax: public static System.Collections.Stack Synchronized (System.Collections.S
2 min read
How to Create Threads in C#?
Multithreading enables concurrent task execution in C#. It improves performance and responsiveness. We can create threads using the System.Threading namespace. With the help of Threads, we can achieve multitasking and can define their behavior using different methods provided by the Thread Class. Ex
6 min read
Task Parallel Library in C#
In C#, Task Parallel Library (TPL) is a collection of APIs that provides more control over parallel and asynchronous programming. It is present in the System.Threading.Tasks namespace. TPL simplifies multithreading by managing thread scheduling and execution efficiently. It includes features like da
9 min read