ChatGPT解决这个技术问题 Extra ChatGPT

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) {...}
What's the return type of ProceesEventAsync?
@tede24 It's Task<InputResult> with InputResult being a custom class.
Your versions are much easier to read in my opinion. However, you have forgotten to Select the results from the tasks before your Where.
And InputResult has a Result property right?
There is also a way for a lazy developer to make this code async. Just add ToList() to create all tasks before waiting for results like so events.Select(async ev => await ProcessEventAsync(ev)).ToList().Select(t => t.Result).... This has a slight performance impact compared to WaitAll() but is negligible in most cases.

E
Ehsan Sajjad
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 await in the select. According to this answer by Stephen Cleary I should be able to drop those.

The call to Select is valid. These two lines are essentially identical:

events.Select(async ev => await ProcessEventAsync(ev))
events.Select(ev => ProcessEventAsync(ev))

(There's a minor difference regarding how a synchronous exception would be thrown from ProcessEventAsync, but in the context of this code it doesn't matter at all.)

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?

It means that the query is blocking. So it is not really asynchronous.

Breaking it down:

var inputs = events.Select(async ev => await ProcessEventAsync(ev))

will first start an asynchronous operation for each event. Then this line:

                   .Select(t => t.Result)

will wait for those operations to complete one at a time (first it waits for the first event's operation, then the next, then the next, etc).

This is the part I don't care for, because it blocks and also would wrap any exceptions in AggregateException.

and is it completely the same like this?

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

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

Yes, those two examples are equivalent. They both start all asynchronous operations (events.Select(...)), then asynchronously wait for all the operations to complete in any order (await Task.WhenAll(...)), then proceed with the rest of the work (Where...).

Both of these examples are different from the original code. The original code is blocking and will wrap exceptions in AggregateException.


Cheers for clearing that up! So instead of the exceptions wrapped up into an AggregateException I would get multiple separate exceptions in the second code?
@AlexanderDerck: No, in both the old and new code, only the first exception would be raised. But with Result it would be wrapped in AggregateException.
I'm getting a deadlock in my ASP.NET MVC Controller using this code. I solved it using Task.Run( … ). I don't have a good feeling about it. However, it finished just right when running into an async xUnit test. What's going on?
@SuperJMN: Replace stuff.Select(x => x.Result); with await Task.WhenAll(stuff)
@DanielS: They're essentially the same. There are some differences such as state machines, capturing context, behavior of synchronous exceptions. More info at blog.stephencleary.com/2016/12/eliding-async-await.html
P
Pang

Existing code is working, but is blocking the thread.

.Select(async ev => await ProcessEventAsync(ev))

creates a new Task for every event, but

.Select(t => t.Result)

blocks the thread waiting for each new task to end.

In the other hand your code produce the same result but keeps asynchronous.

Just one comment on your first code. This line

var tasks = await Task.WhenAll(events...

will produce a single Task so the variable should be named in singular.

Finally your last code make the same but is more succinct.

For reference: Task.Wait / Task.WhenAll


So the first code block is in fact executed synchronously?
Yes, because accessing Result produces a Wait which blocks the thread. In the other hand When produces a new Task you can await for.
Coming back to this question and looking at your remark about the name of the tasks variable, you're completely right. Horrible choice, they're not even tasks as they get awaited right away. I'll just leave the question as is though
Just came by this thread. @AlexanderDerck - why not edit the answer? It gave me confusion for a while before getting to this answer. Also using var usually gets you to this point when it matters.
T
Theodor Zoulias

I used this code:

public static async Task<IEnumerable<TResult>> SelectAsync<TSource,TResult>(
    this IEnumerable<TSource> source, Func<TSource, Task<TResult>> method)
{
  return await Task.WhenAll(source.Select(async s => await method(s)));
}

like this:

var result = await sourceEnumerable.SelectAsync(async s=>await someFunction(s,other params));

Edit:

Some people have raised the issue of concurrency, like when you are accessing a database and you can't run two tasks at the same time. So here is a more complex version that also allows for a specific concurrency level:

public static async Task<IEnumerable<TResult>> SelectAsync<TSource, TResult>(
    this IEnumerable<TSource> source, Func<TSource, Task<TResult>> method,
    int concurrency = int.MaxValue)
{
    var semaphore = new SemaphoreSlim(concurrency);
    try
    {
        return await Task.WhenAll(source.Select(async s =>
        {
            try
            {
                await semaphore.WaitAsync();
                return await method(s);
            }
            finally
            {
                semaphore.Release();
            }
        }));
    } finally
    {
        semaphore.Dispose();
    }
}

Without a parameter it behaves exactly as the simpler version above. With a parameter of 1 it will execute all tasks sequentially:

var result = await sourceEnumerable.SelectAsync(async s=>await someFunction(s,other params),1);

Note: Executing the tasks sequentially doesn't mean the execution will stop on error!

Just like with a larger value for concurrency or no parameter specified, all the tasks will be executed and if any of them fail, the resulting AggregateException will contain the thrown exceptions.

If you want to execute tasks one after the other and fail at the first one, try another solution, like the one suggested by xhafan (https://stackoverflow.com/a/64363463/379279)


This just wraps the existing functionality in a more obscure way imo
The extra parameters are external, depending on the function that I want to execute, they are irrelevant in the context of the extension method.
That's a lovely extension method. Not sure why it was deemed "more obscure" - it's semantically analogous to the synchronous Select(), so is an elegant drop-in.
The async and await inside the first lambda is redundant. The SelectAsync method can simply be written as: return await Task.WhenAll(source.Select(method));
Indeed @Nathan, why have the await at all? - public static Task<TResult[]> SelectAsync<TSource,TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> method) { return Task.WhenAll(source.Select(x => method(x))); }
D
Daryl

I prefer this as an extension method:

public static async Task<IEnumerable<T>> WhenAll<T>(this IEnumerable<Task<T>> tasks)
{
    return await Task.WhenAll(tasks);
}

So that it is usable with method chaining:

var inputs = await events
  .Select(async ev => await ProcessEventAsync(ev))
  .WhenAll()

You shouldn't call the method Wait when it's not actually waiting. It's creating a task that is complete when all of the tasks are complete. Call it WhenAll, like the Task method it emulates. It's also pointless for the method to be async. Just call WhenAll and be done with it.
@AlexanderDerck the advantage is that you can use it in method chaining.
@Servy, actually you can't remove the async and await from the extension method. You get this error: ``` Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'System.Threading.Tasks.Task>' ``` Because it doesn't know Task is covariant with T
@Daryl because WhenAll returns an evaluated list (it's not evaluated lazily), an argument can be made to use the Task<T[]> return type to signify that. When awaited, this will still be able to use Linq, but also communicates that it is not lazy.
Extending @Daryl's good point further, we can reduce further to: public static Task<T[]> WhenAll<T>(this IEnumerable<Task<T> > tasks) { return Task.WhenAll(tasks); }
j
johnny 5

With current methods available in Linq it looks quite ugly:

var tasks = items.Select(
    async item => new
    {
        Item = item,
        IsValid = await IsValid(item)
    });
var tuples = await Task.WhenAll(tasks);
var validItems = tuples
    .Where(p => p.IsValid)
    .Select(p => p.Item)
    .ToList();

Hopefully following versions of .NET will come up with more elegant tooling to handle collections of tasks and tasks of collections.


n
nfplee

I have the same problem as @KTCheek in that I need it to execute sequentially. However I figured I would try using IAsyncEnumerable (introduced in .NET Core 3) and await foreach (introduced in C# 8). Here's what I have come up with:

public static class IEnumerableExtensions {
    public static async IAsyncEnumerable<TResult> SelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector) {
        foreach (var item in source) {
            yield return await selector(item);
        }
    }
}

public static class IAsyncEnumerableExtensions {
    public static async Task<List<TSource>> ToListAsync<TSource>(this IAsyncEnumerable<TSource> source) {
        var list = new List<TSource>();

        await foreach (var item in source) {
            list.Add(item);
        }

        return list;
    }
}

This can be consumed by saying:

var inputs = await events.SelectAsync(ev => ProcessEventAsync(ev)).ToListAsync();

Update: Alternatively you can add a reference to System.Linq.Async and then you can say:

var inputs = await events
    .ToAsyncEnumerable()
    .SelectAwait(async ev => await ProcessEventAsync(ev))
    .ToListAsync();

These two operators are included in the System.Linq.Async package, with the names SelectAwait and ToListAsync, along with lots of other LINQ-style operators.
Actually no, your SelectAsync operates on IEnumerable<T>s. The aforementioned SelectAwait operates on IAsyncEnumerable<T>s. You would need to convert it first, by calling the ToAsyncEnumerable extension method.
Thanks @TheodorZoulias, I've updated my answer with the alternative solution.
K
KTCheek

I wanted to call Select(...) but ensure it ran in sequence because running in parallel would cause some other concurrency problems, so I ended up with this. I cannot call .Result because it will block the UI thread.

public static class TaskExtensions
{
    public static async Task<IEnumerable<TResult>> SelectInSequenceAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> asyncSelector)
    {
        var result = new List<TResult>();
        foreach (var s in source)
        {
            result.Add(await asyncSelector(s));
        }
        
        return result;
    }
}

Usage:

var inputs = events.SelectInSequenceAsync(ev => ProcessEventAsync(ev))
                   .Where(i => i != null)
                   .ToList();

I am aware that Task.WhenAll is the way to go when we can run in parallel.


Upvoted. I would prefer a return type of Task<IList<TResult>> (or even better Task<TResult[]>) instead of Task<IEnumerable<TResult>>. The later conveys the notion of deferred execution, which is not applicable in this case. After the completion of the Task, the resulting IEnumerable<TResult> is fully materialized, since it is based on a List<T>.
F
Florian Winter

"Just because you can doesn't mean you should."

You can probably use async/await in LINQ expressions such that it will behave exactly as you want it to, but will any other developer reading your code still understand its behavior and intent?

(In particular: Should the async operations be run in parallel or are they intentionally sequential? Did the original developer even think about it?)

This is also shown clearly by the question, which seems to have been asked by a developer trying to understand someone else's code, without knowing its intent. To make sure this does not happen again, it may be best to rewrite the LINQ expression as a loop statement, if possible.