Skip to content

Instantly share code, notes, and snippets.

@lukemerrett
Last active November 26, 2018 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukemerrett/867cce0a38b72d0e1e76c83c4b5cdf23 to your computer and use it in GitHub Desktop.
Save lukemerrett/867cce0a38b72d0e1e76c83c4b5cdf23 to your computer and use it in GitHub Desktop.
When Does Await Actually Wait
using System;
using System.Threading;
using System.Threading.Tasks;
namespace WhenDoesAwaitActuallyWait
{
public class Program
{
public static void Main(string[] args)
{
Examples().Wait();
Console.WriteLine("Press enter to quit");
Console.ReadLine();
}
private static async Task Examples()
{
// EXAMPLE 1: Await immediately at the start
var result1 = await LongRunningTask("Task 1");
var result2 = await LongRunningTask("Task 2");
Console.WriteLine("Execution won't continue as we have awaited them immediately, so this only prints at the end");
Console.WriteLine($"Results: {result1}, {result2}");
// EXAMPLE 2: Await tasks individually at the end
var task3 = LongRunningTask("Task 3");
var task4 = LongRunningTask("Task 4");
Console.WriteLine("Execution will continue unimpeded as they aren't awaited yet, this will print whilst these are running");
var result3 = await task3;
var result4 = await task4;
Console.WriteLine($"Results: {result3}, {result4}");
// EXAMPLE 3: Await tasks as a list at the end
var result5 = LongRunningTask("Task 5");
var result6 = LongRunningTask("Task 6");
Console.WriteLine("Execution will continue unimpeded as they aren't awaited yet, this will print whilst these are running");
await Task.WhenAll(new[] { result5, result6 });
Console.WriteLine($"Results: {result5.Result}, {result6.Result}");
}
private static async Task<int> LongRunningTask(string identifier)
{
Console.WriteLine($"Started '{identifier}'");
await Task.Delay(1000);
Console.WriteLine($"Finished '{identifier}'");
return await Task.FromResult(-1);
}
}
}
Started 'Task 1'
Finished 'Task 1'
Started 'Task 2'
Finished 'Task 2'
Execution won't continue as we have awaited them immediately, so this only prints at the end
Results: -1, -1
Started 'Task 3'
Started 'Task 4'
Execution will continue unimpeded as they aren't awaited yet, this will print whilst these are running
Finished 'Task 3'
Finished 'Task 4'
Results: -1, -1
Started 'Task 5'
Started 'Task 6'
Execution will continue unimpeded as they aren't awaited yet, this will print whilst these are running
Finished 'Task 6'
Finished 'Task 5'
Results: -1, -1
Press enter to quit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment