C# Async Task Await

The task namespace provides classes that simplify our writing of parallel and asynchronous codes.

Parallel

If you want to run more than one function at the same time you can do parallel programming by using Task class. Alternatively, you can use the Thread class. However, the Task class contains many useful functions.

We will use the Thread.Sleep function to simulate a long-running function.

If we didn’t use the Task class, it would first do the Islem1 and then do the proccess2.

An example that can be encountered in everyday life is the functions that operate independently of each other. For example, if you were writing a travel planning application, you could have independent functions like RentCar, HotelReservation, BuyAirplaneTicket.

We will use the Stopwatch class to understand how long the functions are running.

All operations will take 6 seconds. Because we didn’t do any parallel programming here. If we turned our code into a parallel program:

When you run the program again, we will first receive the message in seconds. In fact, the whole process doesn’t end in such a short time. But since we didn’t specify how many seconds it takes to wait after all the transactions, we get such a result.

After waiting for all the task, we need to use the Task.WaitAll function to continue our operation.

As we do all the operations in parallel, we will finish our operations in 3 seconds instead of 6 seconds.

Task types

Task types Task types that we have created so far do not return any void type and any values. If the Task function you created returns any value, you must assign the Task type as the type of the returned value.

Asynchronous

Each function in your program may not give you multiple results. A function can query an external source. Such processes often take time. If you want to resume the program according to the result of the process, you need to wait for this process and continue (asynchronous). Thanks to async and await codes, we are able to create an asynchronous function.

async – function type
await – code for wait function result when calling async functions

If the async function returns any value, the function type needs to be a Task

 

 

if you have question do not forget to write from the chat button next to it or from the comment

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *