0

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);
   }
}
TheJediCowboy
  • 8,924
  • 28
  • 136
  • 208

1 Answers1

4

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);
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194