0% found this document useful (0 votes)
3 views

Async_01

The document provides an introduction to asynchronous programming in C#, focusing on the async and await keywords introduced in C# 5.0, which simplify the creation of non-blocking code. It explains the importance of these keywords for developing responsive applications, how to create and call async methods, handle exceptions, and the differences between synchronous and asynchronous programming. Additionally, it includes examples demonstrating the implementation of async and await in various scenarios, highlighting their benefits in maintaining application responsiveness.

Uploaded by

chloekhoury2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Async_01

The document provides an introduction to asynchronous programming in C#, focusing on the async and await keywords introduced in C# 5.0, which simplify the creation of non-blocking code. It explains the importance of these keywords for developing responsive applications, how to create and call async methods, handle exceptions, and the differences between synchronous and asynchronous programming. Additionally, it includes examples demonstrating the implementation of async and await in various scenarios, highlighting their benefits in maintaining application responsiveness.

Uploaded by

chloekhoury2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Introduction to Async and Await in C#

Dr M AOUDE ULFG

February 25, 2024

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 1 / 35


The Evolution of Asynchronous Programming in C#

Asynchronous programming has come a long way in C#. Prior to the


introduction of async and await, developers had to rely on callbacks,
events, and other techniques like the BeginXXX/EndXXX pattern or
BackgroundWorker.
These methods often led to complex and difficult-to-maintain code. With
the release of C# 5.0, async and await keywords were introduced,
simplifying asynchronous programming and making it more accessible to
developers.

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 2 / 35


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# February 25, 2024 3 / 35


Understanding the Async and Await Keywords

The async and await keywords are fundamental to asynchronous


programming in C#. They work together to simplify the process of writing
non-blocking code, making it easier to read and maintain. Let’s take a
closer look at its explanation:

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 4 / 35


Async Keyword

The async keyword is used to mark a method as asynchronous. It indicates


that the method can perform a non-blocking operation and return a Task
or Task< TResult > object. Here are some features of the async
keyword:
It can be applied to methods, lambda expressions, and anonymous
methods.
It cannot be used with properties or constructors.
An async method should contain at least one await expression.
An async method can have multiple await expressions, allowing for
multiple non-blocking operations.
Async methods can be chained together, allowing for complex
asynchronous workflows.

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 5 / 35


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# February 25, 2024 6 / 35
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# February 25, 2024 7 / 35


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# February 25, 2024 8 / 35


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# February 25, 2024 9 / 35


Using Async and Await with Task.Run

To offload CPU-bound work to a separate thread, use Task.Run with


async and await:
1 public async Task P er f o r mC p u B ou n d W or k A sy n c ()
2 {
3 await Task . Run (() = >
4 {
5 // Perform CPU - bound work
6 }) ;
7 }
8

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 10 / 35


Understanding Sync vs. Async in C#

Synchronous programming executes tasks one after another, blocking the


execution flow until each task is completed. On the other hand,
asynchronous programming allows tasks to run concurrently, freeing up the
execution flow to continue with other tasks or operations.

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 11 / 35


Getting Started with Async and Await in C#

Now that we have a basic understanding of asynchronous programming,


let’s explore how C# incorporates async and await keywords to simplify
writing asynchronous code.

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 12 / 35


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# February 25, 2024 13 / 35


Example: Asynchronous Method

1 public async Task DoSomeWorkAsync ()


2 {
3 // Call an asynchronous method and await its
completion
4 await L o n g R u n n i n g O p e r a t i o n A sy n c () ;
5 }
6

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 14 / 35


How to Create an Async Method in C#

To create an async method in C#, follow these steps:


Declare the method with the async keyword.
Ensure the method returns a Task or Task<T> type.
Use the await keyword when calling other async methods within the
method.

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 15 / 35


Example: Async Method

1 public async Task < int > CalculateSumAsync ( int a , int b )


2 {
3 // Simulate a time - consuming operation
4 await Task . Delay (1000) ;
5 return a + b ;
6 }
7

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 16 / 35


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# February 25, 2024 17 / 35


Example: Async Method with Return Value

1 public async Task < string > FetchDataAsync ()


2 {
3 // Call an asynchronous method to fetch data from a
remote source
4 Http R e sp o n se M e ssage response = await httpClient .
GetAsync ( " https :// ul . edu . lb / data " ) ;
5 string content = await response . Content .
ReadAsStri ngAsyn c () ;
6 return content ;
7 }
8

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 18 / 35


Handling Exceptions in Async Methods

Handling exceptions in async methods is similar to handling them in


synchronous methods. Simply use a try-catch block to catch and handle
exceptions.

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 19 / 35


Example: Async Method with Exception Handling

1 public async Task HandleExceptionAsync ()


2 {
3 try
4 {
5 // Call an asynchronous method that might throw an
exception
6 await DoSomeWorkAsync () ;
7 }
8 catch ( Exception ex )
9 {
10 // Handle the exception
11 Console . WriteLine ( $ " Error : { ex . Message } " ) ;
12 }
13 }
14

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 20 / 35


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# February 25, 2024 21 / 35


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# February 25, 2024 22 / 35


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# February 25, 2024 23 / 35


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# February 25, 2024 24 / 35


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# February 25, 2024 25 / 35


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# February 25, 2024 26 / 35


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# February 25, 2024 27 / 35


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# February 25, 2024 28 / 35
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# February 25, 2024 29 / 35


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# February 25, 2024 30 / 35


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# February 25, 2024 31 / 35
Asynchronous Method Calls Example

1 public static void Method3 ( int count )


2 {
3 Console . WriteLine ( " Total count is " + count ) ;
4 }
5 }
6 }

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 32 / 35


Real-time Example

Some APIs that contain async methods are:


HttpClient
SyndicationClient
StorageFile
StreamWriter
StreamReader
XmlReader
MediaCapture
BitmapEncoder
BitmapDecoder
etc.

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 33 / 35


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# February 25, 2024 34 / 35
Real Asynchronous Programming Example

1 Console . WriteLine ( " Total length : " + length ) ;


2 Console . WriteLine ( " After work 1 " ) ;
3 Console . WriteLine ( " After work 2 " ) ;
4 }
5 static async Task < int > ReadFile ( string file )
6 {
7 int length = 0;
8 Console . WriteLine ( " File reading is starting " ) ;
9 using ( StreamReader reader = new StreamReader ( file ) )
10 {
11 string s = await reader . ReadToEndAsync () ;
12 length = s . Length ;
13 }
14 Console . WriteLine ( " File reading is completed " ) ;
15 return length ;
16 }
17 }
18

Dr M AOUDE ULFG Introduction to Async and Await in C# February 25, 2024 35 / 35

You might also like