Skip to content

Instantly share code, notes, and snippets.

@aherrick
Last active April 20, 2024 22:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aherrick/239647bf24bd6483924ce6a22f5c8edf to your computer and use it in GitHub Desktop.
Save aherrick/239647bf24bd6483924ce6a22f5c8edf to your computer and use it in GitHub Desktop.
Task Await Test
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class Program
{
private static async Task Main(string[] args)
{
// first test
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var tGetData1 = GetData1();
var tGetData3 = GetData3();
var tGetData5 = GetData5();
await tGetData5;
await tGetData1;
await tGetData3;
stopWatch.Stop();
Console.WriteLine(stopWatch.Elapsed);
// second test
stopWatch = new Stopwatch();
stopWatch.Start();
var t2GetData1 = GetData1();
var t2GetData3 = GetData3();
var t2GetData5 = GetData5();
await Task.WhenAll(t2GetData1, t2GetData3, t2GetData5);
await t2GetData3;
await t2GetData1;
await t2GetData5;
stopWatch.Stop();
Console.WriteLine(stopWatch.Elapsed);
Console.ReadLine();
}
public static async Task GetData1()
{
await Task.Delay(1000);
}
public static async Task GetData3()
{
await Task.Delay(3000);
}
public static async Task GetData5()
{
await Task.Delay(5000);
}
}
}
@jpwrunyan
Copy link

I assume the intent here is to show that both approaches take the same amount of time (ie 5000 milliseconds).

@plppp2001
Copy link

So how about Task.WhenAll and then just get the .Result of each one after?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment