2

I have following c# code:

list.ForEach(async item =>
await doSomething(item));

and sometimes I am receiving TaskCancelledException.

Why this happens?

Sergiy Kozachenko
  • 1,399
  • 11
  • 31
  • 2
    Don't do this. `List.ForEach()` isn't async-aware. See [this question](http://stackoverflow.com/questions/11564506/nesting-await-in-parallel-foreach) for more information on how to do this properly. – Jeroen Mostert Mar 30 '16 at 12:23
  • 2
    Or this one http://stackoverflow.com/questions/18667633/how-can-i-use-async-with-foreach – CompuChip Mar 30 '16 at 12:23

1 Answers1

0

The type of delegate inside ForEach is Action<T>

Return type of the Action<T> is void that means that yours async item => await doSomething(item) lambda translates into

async void doSomething(T item). Using async with void means that it will be called asynchronously and not be awaited before next iteration happens.

You should always use async with Task return type.

In this example you should use usual foreach

so your example will looks like:

foreach(var item in list) 
{
  await doSomething(item);
}
Sergiy Kozachenko
  • 1,399
  • 11
  • 31