Async await in linq select

后端 未结 7 2333
醉酒成梦
醉酒成梦 2020-12-02 05:30

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

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


        
7条回答
  •  眼角桃花
    2020-12-02 05:50

    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

提交回复
热议问题