0

I have to make multiple Http post requests (few hundreds or can be more) and not wait for any of the responses as have an SLA. Without waiting for those response I need to send back response from my Web API (before performing mentioned multiple HTTP requests, I fetch data from another API and need to return back).

I have looked around and found "fire and forget" implementation which does not wait for response. I am not sure if this right way to do and since im returning without waiting for parallel fire and forget requests, how will HttpClient get disposed?

HttpClient client = new HttpClient();

var CompositeResponse = client.GetAsync(_SOMEURL);

List<MEDLogresp> sortedmeds =   MEDLogresps.OrderBy(x => x.rxId).ThenBy(y => y.recordActionType);

Task.Run(() => Parallel.ForEach(sortedmeds, ele => clientMED.PostAsync(URL , new StringContent(JsonConvert.SerializeObject(ele), Encoding.UTF8, "application/json"))));

return ResponseMessage(Request.CreateResponse<CompositeResponse>(HttpStatusCode.OK, compositeResponse));
Renan
  • 204
  • 1
  • 8
Priya
  • 3
  • 1
  • 3
  • Are you using .net core ? – Ali Alp May 04 '19 at 21:41
  • Right now im using asp.Net web api framework. have plans to migrate to .net core. – Priya May 04 '19 at 21:50
  • In .net core you could use background service [here](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2) after receiving the request just enquue it and it will get it done in the background – Ali Alp May 04 '19 at 21:58
  • Sidenote: for async methods that are dealing with I/O you should use not use Parallel.ForEach. in this particular case it is even wrapped in a completely unnecessary Task.Run – Peter Bons May 05 '19 at 15:41
  • Hi.. im not performing any I/O operations just Posting to an API. The reason i used Task.Run(Parrallel.Foreach) is came across a post doing so as in : https://stackoverflow.com/questions/19102966/parallel-foreach-vs-task-run-and-task-whenall . Please let me know if i should be doing it in other way. Thanks ! – Priya May 06 '19 at 00:32

1 Answers1

0

since im returning without waiting for parallel fire and forget requests, how will httpclient get disposed?

You can use a single, shared static instance of HttpClient for the lifetime of your application and never Dispose() it. It is safe to use the same HttpClient from multiple threads concurrently.

Tim
  • 5,940
  • 1
  • 12
  • 18