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); } } 
0

1 Answer 1

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); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.