Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aaronstaves/8a838dc107ca44af0ebafbbd2ff2791c to your computer and use it in GitHub Desktop.
Save aaronstaves/8a838dc107ca44af0ebafbbd2ff2791c to your computer and use it in GitHub Desktop.
simple async/await example
Console.WriteLine(DateTime.Now);
//This block takes 1 second to run because all 5 tasks are running simultaneously
{
// I would assume these all run IMMEDIATELY
var a = Task.Delay(1000);
var b = Task.Delay(1000);
var c = Task.Delay(1000);
var d = Task.Delay(1000);
var e = Task.Delay(1000);
// Not sure what this is doing ?
await a;
await b;
await c;
await d;
await e;
}
Console.WriteLine(DateTime.Now);
//This block takes 5 seconds to run because each "await" pauses the program until the task finishes
{
// Assuming this runs inside an `await` wrapper at this point, which would make it
// function semi-syncronously, similar to a promise:
await Task.Delay(1000); // .then ...
await Task.Delay(1000); // .then ...
await Task.Delay(1000); // .then ...
await Task.Delay(1000); // .then ...
await Task.Delay(1000);
}
Console.WriteLine(DateTime.Now);
OUTPUT:
5/24/2017 2:22:50 PM
5/24/2017 2:22:51 PM
5/24/2017 2:22:56 PM
@phillijw
Copy link

The "await a, b, c" stuff basically just "awaits" the result from the task above it. It will sit there waiting as long as it needs to for it to finish. IF the task already finished by the time it gets to that point, then it just awaits and keeps on going without taking up additional time

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