I use a set of tasks at times, and in order to make sure everyone is waiting for them, I use this approach:
public async Task ReleaseAsync(params Task[] TaskArray) { var tasks = new HashSet<Task>(TaskArray); while (tasks.Any()) tasks.Remove(await Task.WhenAny(tasks)); }
and then call it like this:
await ReleaseAsync(task1, task2, task3); //or await ReleaseAsync(tasks.ToArray());
However, I recently noticed some strange behavior and decided to check if there was a problem with the ReleaseAsync method. I managed to narrow it down to this simple demo, it works on linqpad if you enabled System.Threading.Tasks . It will also be slightly modified in the console application or in the asp.net mpc controller.
async void Main() { Task[] TaskArray = new Task[]{run()}; var tasks = new HashSet<Task>(TaskArray); while (tasks.Any<Task>()) tasks.Remove(await Task.WhenAny(tasks)); } public async Task<int> run() { return await Task.Run(() => { Console.WriteLine("started"); throw new Exception("broke"); Console.WriteLine("complete"); return 5; }); }
I don’t understand why Exception never appears anywhere. I would think that if expectations are expected, it will be thrown. I was able to confirm this by replacing the while loop with a simple one for everyone, like this:
foreach( var task in TaskArray ) { await task;
My question is why the given example does not correctly throw an exception (it never appears anywhere).
Travis j
source share