Search code examples
c#dotnet-httpclient

Is HttpClient async safe?


I suddenly got some doubts on this. HttpClient is thread safe according to MSDN (for GetAsync or PostAsync at least).

But if I do this

List<Task> tasks= new List<Task>(); 
tasks.Add(_httpClient.PostAsync(url1, requestMessage1));
tasks.Add(_httpClient.PostAsync(url2, requestMessage2));
Tasks.Wait(tasks);

Will I get correct results back all the time as both calls come from the same thread now?


Solution

  • Will I get correct results back all the time as both calls come from the same thread now?

    Yes. That's the indented usage of HttpClient.

    "An HttpClient instance is a collection of settings applied to all requests executed by that instance. In addition, every HttpClient instance uses its own connection pool"

    HttpClient Class