Async 01
Async 01
Dr M AOUDE ULFG
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 1 / 38
The Evolution of Asynchronous Programming in C#
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 2 / 38
The Importance of Async and Await in Modern
Applications
Async and await are essential for creating responsive and scalable
applications. Modern applications often handle multiple tasks
simultaneously, such as fetching data from the internet, processing files, or
performing complex calculations.
By using async and await, developers can offload these tasks to a separate
thread, allowing the main thread to remain responsive and handle user
interactions.
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 3 / 38
Understanding the Async and Await Keywords
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 4 / 38
Async Keyword
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 5 / 38
Await Keyword
The await keyword is used within an async method to temporarily suspend
its execution and yield control back to the calling method until the
awaited task is completed. This allows other tasks to continue executing
in the meantime, ensuring that the application remains responsive. Some
features of the await keyword include:
It can only be used within an async method.
It can be applied to any expression that returns a Task or
Task<TResult> object.
It unwraps the result of the Task<TResult> object, allowing you to
work with the result directly.
It automatically handles exceptions thrown by the awaited task,
allowing you to catch and handle them in the calling async method.
It can be used with using, foreach, and lock statements in C# 8.0
and later.
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 6 / 38
Creating Async Methods
To create an async method, you need to use the async modifier in the
method signature and return a Task or Task<T>:
1 public async Task < string > FetchDataAsync ()
2 {
3 // Perform asynchronous operation
4 }
5
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 7 / 38
Calling Async Methods with Await
To call an async method and wait for its result, use the await keyword:
1 public async Task ProcessDataAsync ()
2 {
3 string data = await FetchDataAsync () ;
4 // Continue processing data
5 }
6
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 8 / 38
Handling Exceptions with Async and Await
When using async and await, handle exceptions using the standard
try-catch block:
1 public async Task ProcessDataAsync ()
2 {
3 try
4 {
5 string data = await FetchDataAsync () ;
6 // Continue processing data
7 }
8 catch ( Exception ex )
9 {
10 // Handle exception
11 }
12 }
13
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 9 / 38
Using Async and Await with Task.Run
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 10 / 38
Understanding Sync vs. Async in C#
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 11 / 38
Getting Started with Async and Await in C#
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 12 / 38
The Basics of Async and Await Keywords
The async and await keywords in C# are used to create and manage
asynchronous methods. Using these keywords makes writing asynchronous
code almost as straightforward as writing synchronous code.
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 13 / 38
Example: Asynchronous Method
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 14 / 38
How to Create an Async Method in C#
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 15 / 38
Example: Async Method
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 16 / 38
Returning Values from Async Methods
Async methods can return values by using the Task<T> type, where T
represents the return value type. Here’s an example:
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 17 / 38
Example: Async Method with Return Value
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 18 / 38
Handling Exceptions in Async Methods
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 19 / 38
Example: Async Method with Exception Handling
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 20 / 38
Async and Await in a Console Application
In this example, we will take two methods that are not dependent on each
other.
1 class Program
2 {
3 static void Main ( string [] args )
4 {
5 Method1 () ;
6 Method2 () ;
7 Console . ReadKey () ;
8 }
9 }
10
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 21 / 38
1 public static async Task Method1 ()
2 {
3 await Task . Run (() = >
4 {
5 for ( int i = 0; i < 100; i ++)
6 {
7 Console . WriteLine ( " Method 1 " ) ;
8 // Do something
9 Task . Delay (100) . Wait () ;
10 }
11 }) ;
12 }
13
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 22 / 38
1 public static void Method2 ()
2 {
3 for ( int i = 0; i < 25; i ++)
4 {
5 Console . WriteLine ( " Method 2 " ) ;
6 // Do something
7 Task . Delay (100) . Wait () ;
8 }
9 }
10 }
11
In the code above, Method1 and Method2 are not dependent on each
other, and we call them from the Main method.
Here, we can see Method1 and Method2 are not waiting for each other.
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 23 / 38
Example: Understanding Async and Await in C#
Please have a look at the below example. It’s a very simple example.
Inside the Main method, first, we print that Main method started, then we
call the SomeMethod. Inside the SomeMethod, first, we print that
SomeMethod started and then the thread execution is sleep for 10. After
10 seconds, it will wake up and execute the other statement inside the
SomeMethod method. Then it will come back to the Main method, where
we called SomeMethod. And finally, it will execute the last print statement
inside the Main method.
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 24 / 38
1 using System . Threading ;
2 namespace A s y n c h ro n ou s Pr og r am m in g
3 {
4 class Program
5 {
6 static void Main ( string [] args )
7 {
8 Console . WriteLine ( " Main Method Started ...... " ) ;
9 SomeMethod () ;
10 Console . WriteLine ( " Main Method End " ) ;
11 Console . ReadKey () ;
12 }
13 public static void SomeMethod ()
14 {
15 Console . WriteLine ( " Some Method Started ...... " ) ;
16 Thread . Sleep ( TimeSpan . FromSeconds (10) ) ;
17 Console . WriteLine ( " \ n " ) ;
18 Console . WriteLine ( " Some Method End " ) ;
19 }
20 }
21 }
22
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 25 / 38
Example: Understanding Async and Await in C#
When you execute the above code, you will see that after printing
SomeMethod Started. . . . . . , the console window is frozen for 10 seconds.
This is because here we are not using asynchronous programming. One
thread i.e. the Main thread is responsible for executing the code And when
we call Thread.Sleep method the current thread is blocked for 10 seconds.
This is a bad user experience.
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 26 / 38
Now, let us see how we can overcome this problem by using asynchronous
programming. Please have a look at the below image. The Thread.Sleep()
is a synchronous method. So, we have changed this to Task.Delay() which
is an asynchronous method. The Task.Delay() method exactly does the
same thing as Thread.Sleep() does.
And, if we want to wait for the task i.e. Task.Delay to be done, then we
have to use the await operator. As we said earlier the await operator is
going to release the current thread that is running from having to wait for
this operation. Therefore, that thread is going to be available for all our
tasks. And then after 10 seconds, the thread will be called to the place
(i.e. Task.Delay()) in order to run the rest code of the SomeMethod. As
we have used await keyword inside the SomeMethod, we must have to
make the SomeMethod as asynchronous as using the async keyword.
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 27 / 38
Asynchronous Programming Example
1 namespace A s y n ch ro n ou s Pr og r am m in g
2 {
3 class Program
4 {
5 static async Task Main ( string [] args )
6 {
7 Console . WriteLine ( " Main Method Started ...... " ) ;
8 await SomeMethod () ;
9 Console . WriteLine ( " Main Method End " ) ;
10 Console . ReadKey () ;
11 }
12 public static async Task SomeMethod ()
13 {
14 Console . WriteLine ( " Some Method Started ...... " ) ;
15 // Use Task . Delay for non - blocking delay
16 await Task . Delay ( TimeSpan . FromSeconds (10) ) ;
17 Console . WriteLine ( " \ n " ) ;
18 Console . WriteLine ( " Some Method End " ) ;
19 }
20 }
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 28 / 38
Asynchronous Method Calls Example
In this example, Method1 returns the total length as an integer value, and
we pass a parameter as a length in Method3, which comes 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.
If we use C# 7 or less, we cannot use the async keyword in the Main
method for the console Application because it will give the error below.
We will create a new method called callMethod, and in this method, we
will call all our Methods Method1, Method2, and Method3, respectively.
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 29 / 38
Asynchronous Method Calls Example
1 namespace A s y n c h ro n ou s Pr og r am m in g
2 {
3 class Program
4 {
5 static void Main ( string [] args )
6 {
7 callMethod () ;
8 Console . ReadKey () ;
9 }
10 public static async void callMethod ()
11 {
12 Task < int > task = Method1 () ;
13 Method2 () ;
14 int count = await task ;
15 Method3 ( count ) ;
16 }
17
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 30 / 38
Asynchronous Method Calls Example
1 public static async Task < int > Method1 ()
2 {
3 int count = 0;
4 await Task . Run (() = >
5 {
6 for ( int i = 0; i < 100; i ++)
7 {
8 Console . WriteLine ( " Method 1 " ) ;
9 count += 1;
10 }
11 }) ;
12 return count ;
13 }
14 public static void Method2 ()
15 {
16 for ( int i = 0; i < 25; i ++)
17 {
18 Console . WriteLine ( " Method 2 " ) ;
19 }
20 }
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 31 / 38
Asynchronous Method Calls Example
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 32 / 38
Real-time Example
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 33 / 38
Real Asynchronous Programming Example
1 using System . IO ;
2 using System . Threading . Tasks ;
3 class Program
4 {
5 static void Main ()
6 {
7 Task task = new Task ( CallMethod ) ;
8 task . Start () ;
9 task . Wait () ;
10 Console . ReadLine () ;
11 }
12 static async void CallMethod ()
13 {
14 string filePath = " E :\\ myFile . txt " ;
15 Task < int > task = ReadFile ( filePath ) ;
16 Console . WriteLine ( " Other Work 1 " ) ;
17 Console . WriteLine ( " Other Work 2 " ) ;
18 Console . WriteLine ( " Other Work 3 " ) ;
19 int length = await task ;
20
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 34 / 38
Real Asynchronous Programming Example
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 35 / 38
Asynchronous Programming in .NET
Support for async/await constructs has been around for more than a
decade. In that time, the way you write scalable code for .NET has
changed, and it’s become extremely common to use functionality without
understanding exactly how it works internally.
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 36 / 38
Synchronous Methods
We’ll start with synchronous methods like the following:
1 // Synchronously copy all data from source to destination .
2 public void C opyStreamToStream ( Stream source , Stream
destination )
3 {
4 var buffer = new byte [0 x1000 ];
5 int numRead ;
6 while (( numRead = source . Read ( buffer , 0 , buffer .
Length ) ) != 0)
7 {
8 destination . Write ( buffer , 0 , numRead ) ;}
9 }
10
These methods are synchronous because the object/code that calls them
isn’t active until those methods are terminated and control reverts back to
the object/code that called them.
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 37 / 38
Asynchronous Method
Now, let’s introduce an asynchronous method:
1 // Asynchronously copy all data from source to
destination .
2 public async Task Co py S tr e am To S tr e am As y nc ( Stream source ,
Stream destination )
3 {
4 var buffer = new byte [0 x1000 ];
5 int numRead ;
6 while (( numRead = await source . ReadAsync ( buffer , 0 ,
buffer . Length ) ) != 0)
7 {
8 await destination . WriteAsync ( buffer , 0 , numRead ) ;
9 }
10 }
11
Dr M AOUDE ULFG Introduction to Async and Await in C# Part 1 March 11, 2024 38 / 38