Asynchronous call in lambda foreach not expected
I have the following method that returns before it completes (method abbreviated for brevity):
private void ProcessAllItems(List<Item> items)
{
items.ForEach(async item =>
{
var response = await Processor.IOBoundTaskAsync(item);
// Some further processing on the response object.
});
}
The Processor.IOBoundTaskAsync method returns a Task <SomeResponseObject> object, not void.
So what's going on?
I want the lambda foreach to process each element one at a time, so not in parallel. For the first iteration, the code goes into IOBoundTaskAsync and comes to the first "wait" (where it calls the first of the 4 expected web service methods), and then the "ProcessAllItems" call method is called.
I am only using test data, so there is only 1 item in my list.
What am I missing?
source to share
List<T>.ForEach
converts your async lambda to async void
, as it accepts Action<T>
. Although it does this, and it has some complexities in handling exceptions, your call ForEach
should work as expected. If not, you may be using the async pattern incorrectly. I would suggest that you set a breakpoint after the first one await
and see the continuation progress.
I would suggest using the usual one instead ForEach
:
private async Task ProcessAllItemsAsync(List<Item> items)
{
foreach (var item in items)
{
var response = await Processor.IOBoundTaskAsync(item);
// Some further processing on the response object.
}
}
Read How to use Async with ForEach? for more details.
source to share