Async_01
Async_01
Dr M AOUDE ULFG
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.
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
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
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
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.
Async methods can return values by using the Task<T> type, where T
represents the return value type. Here’s an example:
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
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.
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.
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.
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.
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