Last active
April 20, 2024 22:48
-
-
Save aherrick/239647bf24bd6483924ce6a22f5c8edf to your computer and use it in GitHub Desktop.
Task Await Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
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
I assume the intent here is to show that both approaches take the same amount of time (ie 5000 milliseconds).