In this code Parallel.ForEach
is not waiting. Seconds elapsed is immediately returning 0. This code is in a PCL:
private void Button_Clicked(object sender, EventArgs e)
{
Stopwatch watch = new Stopwatch();
watch.Start();
List<Task> taskList = new List<Task>();
Task taskA = new Task(ExecuteTaskAAsync);
Task taskB = new Task(ExecuteTaskBAsync);
taskList.Add(taskA);
taskList.Add(taskB);
Parallel.ForEach(taskList, t => t.Start());
watch.Stop();
System.Diagnostics.Debug.WriteLine("Seconds Elapsed: " + watch.Elapsed.Seconds);
}
private async void ExecuteTaskAAsync()
{
for (int i = 0; i < 10; i++)
{
System.Diagnostics.Debug.WriteLine("Task A: [{0}]", i + 1);
await Task.Delay(1000);
}
System.Diagnostics.Debug.WriteLine("Finished Task A!");
}
private async void ExecuteTaskBAsync()
{
for (int i = 0; i < 10; i++)
{
System.Diagnostics.Debug.WriteLine("Task B: [{0}]", i + 1);
await Task.Delay(1000);
}
System.Diagnostics.Debug.WriteLine("Finished Task B!");
}
Responsible for this behavior seems to be t.Start()
, which starts a new thread and Parallel.ForEach
has finished. I also tried it by using Task
as return type and this code:
Parallel.Invoke(async() => await ExecuteTaskAAsync(), async() => await ExecuteTaskBAsync());
Again seconds elapsed is immediately returning 0. How can I run both tasks parallel?