I am trying to follow something give in the below url Async and Await with For Loop
However one thing which i need is to kill all the task if any one of them fails. How can this be done in the LoadAsync method given.
I am trying to follow something give in the below url Async and Await with For Loop
However one thing which i need is to kill all the task if any one of them fails. How can this be done in the LoadAsync method given.
That answer would not work at all because Parallel
is not async aware. The Parallel lambda will simply return immediately with a task being produced. That task is not awaited on. It's thrown away. Therefore the loop will exit immediately after starting all work and not wait for any work to finish.
You can achieve cancellation by first creating a CancellationTokenSource
and passing its Token
property around to all code that you want to cancel. The code must itself pass that token around or periodically check the token.
When you call the Cancel()
method all activity will be signaled to cancel and come to an end.
You can implement the loop using https://blogs.msdn.microsoft.com/pfxteam/2012/03/05/implementing-a-simple-foreachasync-part-2/:
public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body)
{
return Task.WhenAll(
from partition in Partitioner.Create(source).GetPartitions(dop)
select Task.Run(async delegate {
using (partition)
while (partition.MoveNext())
await body(partition.Current);
}));
}