Lets say I run RunSynchron(). In this case it runs Delay() which pause for 10 seconds and while that it continues with the program. After Delay() is done, it returns the value 1 for the if-statement. But why do I have to return a Task<int> instead of an int?
class Synchron
{
public async void RunSynchron()
{
var delay = this.Delay();
Console.WriteLine("Now we wait...");
Console.WriteLine("But we can continue with our work");
if(await delay == 1)
Console.WriteLine("Now it's done");
}
public async Task<int> Delay()
{
await Task.Delay(10000);
return 1;
}
}
Because async keyword is just a syntactic sugar around a method which returns a task. That is its definition.
Under the hood, when the compiler encounters await on the same method call, it will add complete asynchronous call and waiting for completion of the task. Therefore, compiler requires a Task<int> to construct the code for you, the code that ultimately compiles.
Note that the code that follows await is coded as task continuation on the task returned from the method. There is quite a lot of boilerplate if you tried to write it yourself. That is why async/await keywords are so useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With