I am trying to make part of my system run in parallel, but some some reason do it wait for each element before it starts the next even though i have not told it to await. I would like to start executing ExecuteItem for each this.Items and then continue when they are all done.
bool singleThread = false; public async Task Execute() { if (!this.singleThread) { var tasks = this.Items.Select(x => this.ExecuteItem(x)).ToArray(); Task.WaitAll(tasks); } else { foreach (var item in this.Items) { await this.ExecuteItem(item); } } } private async Task ExecuteItem(IMyItem item) { MappedDiagnosticsContext.Set("itemRef", item.ItemRef); try { await this.HandelItem(item); } catch (Exception exp) { Logger.ErrorException(string.Format("Execution for {0} failed.", item.ItemName), exp); Logger.Error("Error Message: ", exp.Message); } MappedDiagnosticsContext.Remove("itemRef"); } To make clear my problem my code behaves as if had wrote the following
var tasks = this.Items.Select(x => await this.ExecuteItem(x)).ToArray(); To make sure it was not some kind of linq problem have i rewriten the problem code to the following, however the code still blocks tasks[i] = this.ExecuteItem(this.Items[i]);
Task[] tasks = new Task[this.Items.Count]; for (int i = 0; i < this.Items.Count; i++) { Console.WriteLine("Adding " + this.Items[i].ItemName); tasks[i] = this.ExecuteItem(this.Items[i]); } Console.WriteLine("Waiting!!!"); Task.WaitAll(tasks);
awaitfor each one.