I want to start a collection of Task
objects at the same time and wait until all are complete. The following code shows my desired behaviour.
public class Program
{
class TaskTest
{
private Task createPauseTask(int ms)
{
// works well
return Task.Run(async () =>
// subsitution: return new Task(async () =>
{
Console.WriteLine($"Start {ms} ms pause");
await Task.Delay(ms);
Console.WriteLine($"{ms} ms are elapsed");
});
}
public async Task Start()
{
var taskList= new List<Task>(new[]
{
createPauseTask(1000),
createPauseTask(2000)
});
// taskList.ForEach(x => x.Start());
await Task.WhenAll(taskList);
Console.WriteLine("------------");
}
}
public static void Main()
{
var t = new TaskTest();
Task.Run(() => t.Start());
Console.ReadKey();
}
}
The output is:
Start 1000 ms pause
Start 2000 ms pause
1000 ms are elapsed
2000 ms are elapsed
------------
Now I wonder if it is possible to prepare my tasks and start them separately. In order to do that I change the first line in createPauseTask(int ms)
method from return Task.Run(async () =>
to return new Task(async () =>
and in the Start()
method I included a taskList.ForEach(x => x.Start());
before the WhenAll
. But then terrible things happen. The WhenAll
call completes immediately and the output is:
Start 2000 ms pause
Start 1000 ms pause
------------
1000 ms are elapsed
2000 ms are elapsed
Can someone show me what my mistake is and how to fix it?