Priya
Priya

Reputation: 3

Handling HTTPClient performing multiple requests in fire and forget

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

Upvotes: 0

Views: 3504

Answers (1)

Tim
Tim

Reputation: 6060

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.

Upvotes: 0

Related Questions