первый пример дела
foreach (Task task in tasks)
{
await Task.Run(() => task);
}
должен быть изменен на
foreach (Task task in tasks)
{
task.Start(); // there is no sense to await since tasks should be run in parallel I suppose
}
Однако второй случай неясен. Вы запускаете второй случай после первого? Хорошо, если у вас tasks
только что инициализирован перед вызовом Start
, как
List<Task> tasks = new List<Task>()
{
new Task(() => this.firstMethod()),
new Task(() => this.secondMethod()),
};
foreach (Task task in tasks)
{
task.Start();
task.Wait(); // this causes tasks to be run in sequence (one by one) like with await in the first sample
}
. Самый простой случай - использовать Task.Run
var tasks = new[Task]
{
Task.Run(firstMethod),
Task.Run(secondMethod),
}; // tasks are started immediately there is no need to start them later
Task.WaitAll(tasks); // wait until all tasks are finished