Search code examples
c#mstestxunitdotnet-httpclientvisual-studio-test-runner

HttpClient.PostAsync() method is hanging forever in C# xUnt test


I have 600 functional xUnit tests and each of the test is calling a httpClient.GetAsync(apiUrl) and httpClient.PostAsync(apiUrl, data) methods in the middle of the test which will call some external APIs.

When I execute each test sequentially all working fine. Also even when I run 5 - 6 test cases parallelly then also everything works fine.

My problem is, when I start all 600 test cases from the top (which will start around 50 out 600 test cases parallelly), all the tests are hanging where it sends the httpClient.PostAsync(apiUrl, data) method.

The same issue happened at the point where it executes the httpClient.GetAsync(apiUrl) method. But after I change it as httpClient.GetAsync(apiUrl).ConfigureAwait(false) it fix the issue.

But when I change the httpClient.PostAsync(apiUrl, data) to httpClient.PostAsync(apiUrl, data).ConfigureAwait(false) issue is still the same.

Can someone explain why this happens and what should I do to fix this issue.


Solution

  • When I change the httpClient.PostAsync(apiUrl, data) method as below, it fix the issue. I'm not sure what the difference between two methods.

    Previous way

    var response = await httpClient.PostAsync(apiUrl, data);
    

    I modified above as below and it fixed the issue.

    var task = httpClient.PostAsync(apiUrl, data);
    var response = task.GetAwaiter().GetResult();
    

    Also I found some similar problem that has been discussed in below post. If someone facing similar issue, please follow below post as it contains some more useful tips and reasons. HttpClient.GetAsync(...) never returns when using await/async