Async await in linq select

I need to modify an existing program and it contains following code:

var inputs = events.Select(async ev => await ProcessEventAsync(ev))
                   .Select(t => t.Result)
                   .Where(i => i != null)
                   .ToList();

But this seems very weird to me, first of all the use of async and awaitin the select. According to this answer by Stephen Cleary I should be able to drop those.

Then the second Select which selects the result. Doesn’t this mean the task isn’t async at all and is performed synchronously (so much effort for nothing), or will the task be performed asynchronously and when it’s done the rest of the query is executed?

Should I write the above code like following according to another answer by Stephen Cleary:

var tasks = await Task.WhenAll(events.Select(ev => ProcessEventAsync(ev)));
var inputs = tasks.Where(result => result != null).ToList();

and is it completely the same like this?

var inputs = (await Task.WhenAll(events.Select(ev => ProcessEventAsync(ev))))
                                       .Where(result => result != null).ToList();

While i’m working on this project I’d like to change the first code sample but I’m not too keen on changing (apparantly working) async code. Maybe I’m just worrying for nothing and all 3 code samples do exactly the same thing?

ProcessEventsAsync looks like this:

async Task<InputResult> ProcessEventAsync(InputEvent ev) {...}

8 Answers
8

Leave a Comment