I was learning how do async and await work in programming. I came across this example on the internet saying that this is asynchronous code:
class Program
{
static async Task Main(string[] args)
{
Method2();
var count = await Method1();
Method3(count);
Console.ReadKey();
}
static async Task<int> Method1()
{
int count = 0;
await Task.Run(() =>
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(" Method 1");
count += 1;
}
});
return count;
}
static void Method2()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(" Method 2");
}
}
static void Method3(int count)
{
Console.WriteLine("Total count is " + count);
}
}
Asynchronous programming is a form of concurrent programming that allows two separate pieces of code to run simultaneously, as I understand it. But all these await operators make the code run consistently and actually, we could use the following example, which gives the same output:
class Program
{
static async Task Main(string[] args)
{
Method2();
Method3(Method1());
Console.ReadKey();
}
static int Method1()
{
int count = 0;
for (int i = 0; i < 3; i++)
{
Console.WriteLine(" Method 1");
count += 1;
}
return count;
}
static void Method2()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine(" Method 2");
}
}
static void Method3(int count)
{
Console.WriteLine("Total count is " + count);
}
}
So why do I use await operators when they essentially make asynchronous code synchronous?