I have following c# code:
list.ForEach(async item =>
await doSomething(item));
and sometimes I am receiving TaskCancelledException.
Why this happens?
I have following c# code:
list.ForEach(async item =>
await doSomething(item));
and sometimes I am receiving TaskCancelledException.
Why this happens?
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);
}