Intro
Hello and welcome back to the second tutorial in our C# series, C# Keywords, where we are going to learn about all the C# keywords out there!.
Async and Await?
Today we will learn about 2 keywords since these two keywords always come together as a package!.
They are the Async and Await!.
We can use the async modifier to specify that a method, lambda expression, or anonymous method is asynchronous. If you use this modifier on a method or expression, it’s referred to as an async method.
An async method runs synchronously until it reaches its first await expression, at which point the method is suspended until the awaited task is complete. In the meantime, control returns to the caller of the method, as the example in the next section shows.
So let’s look at an example !.
Let’s make a mockup of a long task.
static async Task<Task> Count(int count)
{
//count from 1 to count
for (int i = 1; i <= count; i++)
{
//print the progress
Console.WriteLine(i);
//wait for 1 second
await Task.Delay(1000);
}
//return task completed to indicate that this task is finished
return Task.CompletedTask;
}
then in our main method let’s call our Count task, the catch is that we need to wait for the Count to be done to continue.
using System;
using System.Threading.Tasks;
namespace Keyword_Series
{
class Program
{
//change our Main to be async so we can await tasks
static async Task Main(string[] args)
{
//start the count task and wait for it to be finished
await Count(10);
Console.WriteLine("Finished Counting!");
}
}
}
What now ?.
Now async operations can be divided into two types:
IO Bound and Network Bound Operations !.
And of course, they are useful when you try to do more than one task at the same time!.
Which we already covered in this C# tutorial so check it out !.