I have a collection of tasks that have to finish before one last task is run. Specifically:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var task1 = Task.Run(() =>
{
Thread.Sleep(5000);
Console.WriteLine("Task1");
});
var task2 = Task.Run(() =>
{
Thread.Sleep(5000);
Console.WriteLine("Task2");
});
var task3 = Task.Run(() =>
{
Thread.Sleep(5000);
Console.WriteLine("Task2");
});
var last = Task.Run(() =>
{
Console.WriteLine("Last");
});
var tasks = new List<Task>();
tasks.Add(task1);
tasks.Add(task2);
tasks.Add(task3);
await Task.WhenAll(tasks).ContinueWith(t => last);
}
Currently they finish like this:
Last
Task2
Task3
Last1
I want them to finish like this:
Task1
Task2
Task3
Last
The order of first 3 does not matter, what matters is that Last task finishes last. I cannot block the thread or wait for the collection to finish and similar stuff, only the Last task has to perform after first three are done.