I'm trying to understand async/await in C#. I have two methods here to explain. With Method1 I understand that the creation of the Task begins the execution of the LongRunningOperationAsync(), and now we can do other things before awaiting the result, so two things are happening at the same time. In the real world I see a lot of code like Method2, and I cannot see the advantage of using async/await in this case. I've done a lot of reading but it's just not clicking. Please help.
class Program
{
public static async Task Main()
{
await MyMethodAsync1();
//await MyMethodAsync2();
}
public static async Task MyMethodAsync1()
{
Task<int> longRunningTask = LongRunningOperationAsync();
// long op method is now running so can do independent work
// which doesn't need the result of long op
await Task.Delay(1000);
int result = await longRunningTask;
Console.WriteLine("MyMethodAsync1() finished");
}
// This method just awaits the long op method directly,
// so doesn't seem to have any benefit
public static async Task MyMethodAsync2()
{
int result = await LongRunningOperationAsync();
Console.WriteLine("MyMethodAsync2() finished");
}
public static async Task<int> LongRunningOperationAsync()
{
Console.WriteLine("LongRunningOperationAsync() started");
await Task.Delay(2000);
Console.WriteLine("LongRunningOperationAsync() finished");
return 1;
}
}