0% found this document useful (0 votes)
8 views26 pages

Async 02

The document discusses asynchronous programming in C#, focusing on the use of async and await keywords to improve application responsiveness and resource management. It outlines the benefits and limitations of asynchronous programming, provides examples of its application in desktop and web server environments, and details how to implement async methods using the .NET framework. Additionally, it covers the process of converting synchronous methods to asynchronous ones and explains the underlying mechanics of async methods in C#.

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)
8 views26 pages

Async 02

The document discusses asynchronous programming in C#, focusing on the use of async and await keywords to improve application responsiveness and resource management. It outlines the benefits and limitations of asynchronous programming, provides examples of its application in desktop and web server environments, and details how to implement async methods using the .NET framework. Additionally, it covers the process of converting synchronous methods to asynchronous ones and explains the underlying mechanics of async methods in C#.

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/ 26

Async and Await in C# Part 2

Dr M AOUDE ULFG

March 11, 2024

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 1 / 26


Asynchronous Programming

What is Asynchronous Programming?


When a computer runs a program, it allocates a thread to execute the
application code.
In synchronous programming, all code runs on a single thread,
causing operations to execute one at a time. If one operation takes a
long time, the program freezes until it completes.
Asynchronous operations run on separate threads initiated from
another thread, allowing the initiating thread to continue without
waiting for the operation to finish. This enables the allocation of
resources to other tasks in the meantime.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 2 / 26


Asynchronous Programming

Why use Asynchronous Programming?


Asynchronous programming efficiently utilizes machine resources,
particularly for long-running operations, making applications more
responsive, interactive, and user-friendly.
It also leverages parallel computing, simplifying the development of
parallel processing applications without complex code.
When to use Asynchronous Programming
Asynchronous code is ideal for long-running operations, such as
I/O-bound or CPU-bound tasks, including network requests, disk
operations, and scientific calculations.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 3 / 26


Asynchronous Programming

Applications Best Suited for Asynchronous Programming


Desktop User Interface Applications: Asynchronous programming
ensures responsiveness and interactivity in UI applications, preventing
freezes during long-running operations.
Web Server Applications: Asynchronous programming optimizes
server performance, handling multiple client requests efficiently
without delays.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 4 / 26


Asynchronous Programming: Limitations

Asynchronous Programming is not Always the Solution


Asynchronous code does not automatically improve performance. It
helps manage resources more efficiently but does not reduce the time
taken for tasks such as network operations.
Using Asynchronous code imposes overhead on the system. This
includes memory overhead, where each thread reserves memory, and
scheduler overhead, where the operating system manages thread
execution. Excessive thread usage can slow down the entire system.
If you don’t have a desktop/UI application, or your code is not
network or I/O-bound, you may not see significant benefits from
asynchronous programming.
For CPU-bound applications (slowing down due to heavy compute
processes), multi-threading or task-based asynchrony is a more
suitable solution.
Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 5 / 26
Async and Await Keywords

Async and Await Keywords


Asynchronous operations in the .NET Framework are closely related
to tasks. The support for async programming in .NET makes it easier
to perform asynchronous operations by transparently creating new
tasks and coordinating their actions.
The heart of async programming in C# lies in the built-in async and
await keywords. These keywords enable you to invoke an
asynchronous operation and wait for the result within a single
method, without blocking the thread.
Async Methods
Asynchronous methods defined using async and await are referred to
as async methods. They allow you to write code that executes
asynchronously without the need for complex threading mechanisms.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 6 / 26


Asynchronous Method

1 // Three things to note in the signature :


2 // - The method has an async modifier .
3 // - The return type is Task or Task <T >.
4 // Here , it is Task < int > because the return statement
returns an integer .
5 // - The method name ends in " Async ."
6 async Task < int > AccessTheWebAsync ()
7 {
8 // You need to add a reference to System . Net . Http to
declare client .
9 HttpClient client = new HttpClient () ;
10 // GetStringAsync returns a Task < string >. That means
that when you await the task you ’ ll get a string (
urlContents ) .
11 Task < string > getStringTask = client .
GetStringAsync ( " http :// ul . edu . lb " ) ;
12 // You can do work here that doesn ’ t rely on the
string from GetStringAsync .
13 DoIndependentWork () ;
14
Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 7 / 26
Asynchronous Method

1
2 // The await operator suspends AccessTheWebAsync .
3 // - AccessTheWebAsync can ’ t continue until
getStringTask is complete .
4 // - Meanwhile , control returns to the caller of
AccessTheWebAsync .
5 // - Control resumes here when getStringTask is
complete .
6 // - The await operator then retrieves the string
result from getStringTask .
7 string urlContents = await getStringTask ;
8 // If AccessTheWebAsync doesn ’ t have any work that it
can do // between calling GetStringAsync and awaiting
its completion , you // can simplify your code by calling
and awaiting in the following // single statement .
9 string urlContents = await client . GetStringAsync () ;
10 // The return statement specifies an integer result .
11 // Any methods that are awaiting AccessTheWebAsync
retrieve the length value .
12 return urlContents . Length ;
13 Dr M}AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 8 / 26
Characteristics of Async Methods
What makes an async method?
The method signature includes an async modifier.
By convention, the name of an async method ends with an ”Async”
suffix.
The return type is one of the following types:
1 Task<TResult >
2 Task
3 void
The method includes at least one await expression, such as:
string urlContents = await getStringTask;

This marks a point where the method can’t continue until the awaited
asynchronous operation is complete. In the meantime, the method is
suspended, and control returns to the method’s caller.
Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 9 / 26
Async Method Return Types

When defining an async method, the return type should be chosen based
on the scenario. Here are the valid return types for an async method:
Task¡TResult¿: Use this return type if your method has a return
statement where the operand has type TResult.
Task: If your method has no return statement or has a return
statement with no operand, you should use this return type.
void: If you’re writing an async event handler, the return type should
be void.
Any other type with a GetAwaiter method: In some cases, you
may define an async method with a custom return type that
implements a GetAwaiter method.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 10 / 26


Core of Asynchronous Programming
The core of asynchronous programming in C# revolves around the
Task and Task<T > objects, which model asynchronous operations.
Task objects represent ongoing operations, while Task<T > objects
represent operations that will have a result of type T at some point in
the future. They serve as promises of a result when the awaited
operation completes.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 11 / 26


I/O-Bound Example: Downloading Data from a Web
Service
You may need to download some data from a web service when a button is
pressed, but don’t want to block the UI thread.
1 private readonly HttpClient _httpClient = new HttpClient
() ;
2
3 downloadButton . Clicked += async (o , e ) = >
4 {
5 // This line will yield control to the UI as the
request
6 // from the web service is happening .
7 // The UI thread is now free to perform other work .
8 var stringData = await _httpClient . GetStringAsync ( URL )
;
9 DoSo m e th i n gW i t hData ( stringData ) ;
10 };
11

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 12 / 26


CPU-bound Example: Performing a Calculation for a Game

Say you’re writing a mobile game where pressing a button can inflict
damage on many enemies on the screen. Performing the damage
calculation can be expensive, and doing it on the UI thread would make
the game appear to pause as the calculation is performed!
The best way to handle this is to start a background thread which does
the work using Task.Run, and await its result. This will allow the UI to
feel smooth as the work is being done.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 13 / 26


CPU-bound Example: Performing a Calculation for a Game
1 private DamageResult CalculateDamageDone ()
2 {
3 // Code omitted :
4 //
5 // Does an expensive calculation and returns
6 // the result of that calculation .
7 }
8
9 calculateButton . Clicked += async (o , e ) = >
10 {
11 // This line will yield control to the UI while
Calcula t e Da m a ge D o ne ()
12 // performs its work . The UI thread is free to
perform other work .
13 var damageResult = await Task . Run (() = >
Calcula t e Da m a ge D o ne () ) ;
14 DisplayDamage ( damageResult ) ;
15 };
16

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 14 / 26


Async Method Support in .NET Core Framework
The .NET Core framework provides rich support for async methods. Types
in the .NET Core framework that have support for async methods include:
Network-oriented classes with async methods:
HttpClient: Provides a base class for sending HTTP requests and
receiving HTTP responses from a resource identified by a URI.
WebClient: Provides common methods for sending data to and
receiving data from a resource identified by a URI.
Files I/O-oriented classes with async methods:
StreamWriter: Provides methods for writing characters to a stream in a
particular encoding.
StreamReader: Allows reading of characters from a byte stream in a
particular encoding.
XmlReader: Represents a reader that provides fast, non-cached,
forward-only access to XML data.
You can refer to the links for complete references on using these types
with async methods.
Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 15 / 26
Using HttpClient in C# for HTTP Operations

In modern software development, making HTTP requests to interact with


web APIs or consume web services is a common requirement. C#
developers can leverage the powerful HttpClient class to handle such
requests effectively. In this article, we will explore how to use HttpClient
in C# to perform various HTTP operations, including GET, POST, PUT,
DELETE, and how to handle response data.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 16 / 26


Making a GET Request

Now that we have an HttpClient instance, let’s see how to make a


simple GET request to a web API endpoint and retrieve data.
1 string apiUrl = " https :// api . example . com / data " ;
2 Http R e sp o n se M e ssage response = await httpClient .
GetAsync ( apiUrl ) ;
3
4 if ( response . IsSuccessStatusCode )
5 {
6 string responseContent = await response . Content .
ReadAsStri ngAsyn c () ;
7 // Process the response data here
8 }
9

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 17 / 26


Making a POST Request

To send data to the server using the POST method, you can use the
PostAsync method.
1 string apiUrl = " https :// api . example . com / data " ;
2 var data = new StringContent ( " {\" name \":\" John \" ,\" age
\":30} " ,
3 Encoding . UTF8 , " application / json " ) ;
4
5 HttpRes p o ns e M es s age response = await httpClient .
PostAsync ( apiUrl , data ) ;
6 if ( response . Is S uccessStatusCode )
7 {
8 string responseContent = await response . Content .
ReadAsStri ngAsyn c () ;
9 // Process the response data here
10 }
11

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 18 / 26


Identifying Entry Points for Asynchronous Code

When using asynchronous programming, the next step is to identify the


entry point of asynchronous code. This involves determining where async
methods should start and where to await on calls. For example:
Determine where to call a web service in the code (e.g., when a user
clicks on a button or when a web server receives a request from a
client).
Another strategy is to start with synchronous code, especially with
network- or I/O-bound operations. Then, you can gradually convert your
synchronous code to asynchronous code by following these steps:
Add the await keyword for calling code.
Add the async keyword for the method making the await call.
Adjust return types accordingly.
Modify calling methods on the call stack to also be asynchronous.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 19 / 26


Converting a Synchronous Method to an Asynchronous
Method
Converting a synchronous method to an asynchronous method:
private void WebPage(string someURI)
{
WebClient webClient = new WebClient();
string pageContent = webClient.DownloadString(someURI);
Console.WriteLine(pageContent);}

And here is the method after converting it to use async:


private async void WebPageAsync(string someURI)
{
WebClient webClient = new WebClient();
string pageContent = await webClient.DownloadStringTaskAsyn
Console.WriteLine(pageContent); }

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 20 / 26


Understanding What Happens Behind the Scenes

How Does an Async Method Work?


In async methods, you use the proper keywords and types to indicate what
you want to do, and the compiler does the rest, including keeping track of
what must happen when control returns to an await point in a suspended
method. In this lesson, we will explore what happens behind the scenes.
The .NET Framework simplifies many operations to allow methods to
be async. It does a lot of work that you do not have to write code for
unless you were writing asynchronous code manually. Examples of
these operations are:
1 Saving state.
2 Saving the parameters of your method.
3 Saving local variables; any other variables in scope.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 21 / 26


Understanding What Happens Behind the Scenes

The .NET Framework saves the location in your method where the
asynchronous thread starts to be able to resume back to the right
step in the execution.
The .NET Framework saves the context of the current thread which
includes:
1 Execution Context.
2 Security Context.
3 Call Context.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 22 / 26


Async Method Overview

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 23 / 26


Async Method Overview

Step 1: An event handler calls and awaits the AccessTheWebAsync


async method.
Step 2: AccessTheWebAsync creates an HttpClient instance and
calls the GetStringAsync asynchronous method to download the
contents of a website as a string.
Step 3: Something happens in GetStringAsync that suspends its
progress. Perhaps it must wait for a website to download or some
other blocking activity. To avoid blocking resources,
GetStringAsync yields control to its caller, AccessTheWebAsync.
Step 4: Because getStringTask hasn’t been awaited yet,
AccessTheWebAsync can continue with other work that doesn’t
depend on the final result from GetStringAsync. That work is
represented by a call to the synchronous method
DoIndependentWork.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 24 / 26


Async Method Overview

Step 5: DoIndependentWork is a synchronous method that does its


work and returns to its caller.
Step 6: AccessTheWebAsync has run out of work that it can do
without a result from getStringTask. AccessTheWebAsync next
wants to calculate and return the length of the downloaded string,
but the method can’t calculate that value until the method has the
string. Therefore, AccessTheWebAsync uses an await operator to
suspend its progress and to yield control to the method that called
AccessTheWebAsync. AccessTheWebAsync returns a Task<int> to
the caller.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 25 / 26


Async Method Overview

Step 7: GetStringAsync completes and produces a string result.


The string result isn’t returned by the call to GetStringAsync in the
way that you might expect. Instead, the string result is stored in the
task that represents the completion of the method, getStringTask.
The await operator retrieves the result from getStringTask. The
assignment statement assigns the retrieved result to urlContents.
Step 8: When AccessTheWebAsync has the string result, the method
can calculate the length of the string. Then the work of
AccessTheWebAsync is also complete, and the waiting event handler
can resume.

Dr M AOUDE ULFG Async and Await in C# Part 2 March 11, 2024 26 / 26

You might also like