Can this async/await code be rewritten using Task.WhenAll(...) or something else that makes more sense then awaiting each time?

I have the following piece of code (changed the names of my classes/objects for brevity). It essentially is hitting an external API that allows only a single operation, but my service code will expose it as a bulk type request.

It doesn't seem right to await on each async request, but instead dispatch all the requests and just wait for all of them. I could be wrong tho.

public async void SendSeveralRequestsAsync(MyClass myClass)
{
   var client = SomeExternalServiceClient();

   foreach(var item in myClass)
   {
        var singleAsyncRequest = new ExternalServiceRequest()
        {
            Value = item.Value
        };

        var response = await client.SendAsync(singleAsyncRequest);
   }
}
Jon Skeet
people
quotationmark

Yes, you should be able to use something like:

public async void SendSeveralRequestsAsync(MyClass myClass)
{
   var client = SomeExternalServiceClient();
   var tasks = myClass
       .Select(item => new ExternalServiceRequest { Value = item.Value })
       .Select(request => client.SendAsync(request));
   await Task.WhenAll(tasks);
}

Or perhaps even better - as I don't like returning void from an async method other than for events:

public Task SendSeveralRequestsAsync(MyClass myClass)
{
   var client = SomeExternalServiceClient();
   var tasks = myClass
       .Select(item => new ExternalServiceRequest { Value = item.Value })
       .Select(request => client.SendAsync(request));
   return Task.WhenAll(tasks);
}

people

See more on this question at Stackoverflow