Do you want to use async/await on c# ? (yes, as in javascript) Okey, I'll show you how to do that in an easy way 😎
First of all
You should have your project on c# (.net core/framework) created.
Let's start
There are a few concepts that you need to know, so this tutorial is divided into several small sections:
We can see, 3 elements: Output:Task class 🧙 your best friend
The task class on c# represents an async operation, this operation can be a simple method wich will be called without interrupt the current process thread, it'll run on another Thread, but you don't have to do any complex syntax, just call a method.
Hello! this will run async
A more detailed example 👀
The task class is a powerful tool of c#, but maybe you got confused on how and when it is running.
Well this is a more detailed example, we have 2 tasks to do:
As you can see, the 2 tasks are example operations wich use Thread.Sleep(miliseconds)
function to stop temporaly the task thread (to simulate a real operation).
So, let's Start
these tasks and check it's behaviour:
Output
Starting all tasks
Starting task 1
Starting task 2
------------------------------------
All tasks have finished, or not?
Task 1 done
Task 2 done
As we can see, the 2 tasks have been called asynchronously, and it's output is on the bottom.
But what happend with the All tasks have finished, or not?
line, it should appear after tasks have been done, how can we do that? It's very easy, and we'll see it on the next section
Now, this method is able to "await" a So, we can modify the example of the previous section to make it an async method: As we can see, the code is inside of an async method called Now, the task 1 will start with The output: We have fixed the problems we saw in the previous section.Async/Await 🪄
Async/Await in c# is simple. You just have to put the async
word in a method, example:
public void DoSomething()
to public async void DoSomething()
.
Task
until it finishes its work, using the await
word before the task name 🤯
Main
. Also, we add await task
, this will allow us to control the code flow.task1.Start()
normally, but the await task1
statement won't allow the code execution to continue until the task 1 has finished. The same behaviour for the task 2.
Starting all tasks
Hello! this will run async
Starting task 1
Task 1 done
Starting task 2
Task 2 done
------------------------------------
All tasks have finished, or not?
All tasks have finished, or not?
is at the end
The Async/Await and Task class are powerful tools to make concurrent, efficient and legible code without much effort 🚀.
There are more useful uses of these features, you can leave me a comment if you want more tutorials about C# or something else 👀
Top comments (1)
More info from official documentation: