I have a set of Task (there are a lot of them, about 400):
IEnumerable<Task> tasks = ...
I want to run them all at the same time and then wait for each of them. I use this piece of code to complete tasks:
Task.Run(async () => { ... });
Each of the tasks will run asynchronous methods on its own, and so I need the async in lambda. Among these nested tasks, there are well-known HTTP requests that are sent, and HTTP responses that are received.
I tried two different ways to wait for all tasks to complete:
await Task.WhenAll(tasks);
and
foreach (var task in tasks) { await task; }
Which, a priori, look the same for me (but, of course, they seem to be wrong, I would not publish here in the first place ...).
The first method makes tasks run faster, but there are tons of A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll and other similar ones in the output window. Moreover, some tasks are still in the WaitingForActivation state after calling await Task.WhenAll() .
The second method is slower, and it seems that the tasks are not running at the same time (I get HTTP responses one by one, and the first method of waiting for tasks makes them come almost all at the same time). In addition, I see no first chance exception at all in the output window, when I use the foreach to wait for each task, and no task has a WaitingForActivation state after the loop.
I understand that the βbestβ way to wait for a set of tasks is to use WhenAll() (at least for reading), but why do these two methods behave differently? How can I solve this problem? Ideally, I would like the tasks to be executed quickly and be sure that everything is over (I have a try catch finally catch in lambda to handle server error, and I did not forget if(httpClient != null) httpClient.Dispose() in finally before anyone asks ...).
Any hints are welcome!
EDIT
Ok, I tried another. I added:
.ContinueWith(x => System.Diagnostics.Debug.WriteLine("#### ENDED = " + index)));
For each task, index is the Task number. When using the foreach I get:
When using WhenAll() I get:
Thus, using the foreach , all my tasks are executed synchronously ..., which perhaps explains why I do not get any first chance exception in the output window, since the system is not criticized at all by the algorithm.
EDIT2:
Sample code: http://pastebin.com/5bMWicD4
The public service is used here: http://timezonedb.com/