It's actually a lot simpler than Solution #1:
public static async Task HelloDelay(string message, Action<string> callback, int millisecondsDelay)
{
Console.WriteLine("HelloDelay({0}) loading", millisecondsDelay);
await Task.Delay(millisecondsDelay);
callback(message);
}
public static async Task Run()
{
var task9000 = HelloDelay("HelloDelay(9000) ended", Console.WriteLine, 9000);
var task6000 = HelloDelay("HelloDelay(6000) ended", Console.WriteLine, 6000);
var task3000 = HelloDelay("HelloDelay(3000) ended", Console.WriteLine, 3000);
await Task.WhenAll(task9000, task6000, task3000);
}
Use
the Task.Delay
method[
^] to pause the task, rather than sitting in a tight loop checking the elapsed time.
That pushes the execution onto a continuation, so you no longer need the
Task.Run
call.
Avoid "async void" wherever possible:
Avoid async void methods - Phil Haack[
^]
I've merged the three "hello" methods into a single method, since they only vary by the delay time, which can be passed as a parameter. If necessary, you could create three copies of the method without the
millisecondsDelay
parameter, and hard-code the delay within the methods.