MDK
MDK

Reputation: 505

HttpClient PostAsync is blocking

I am trying to call HttpClient.PostAsync() from my UI thread. I have tested this on my development machine and it works fine but on my target machine is seems to block the UI thread. I ran this test on both machines

int tick = Environment.TickCount;
Task<HttpResponseMessage> postTask = _httpClient.PostAsync(Uri,
    new StringContent(messageString));
MessageBox.Show(String.Format("Time {0}", Environment.TickCount - tick));
response = await postTask;

On my development machine the message box shows ~<100ms however on the target machine it is excess of 2.5 seconds. Is there something that I am missing or is there some setting/OS/hardware support required.

Upvotes: 0

Views: 1574

Answers (2)

MDK
MDK

Reputation: 505

For future reference I think I found the solution. It looks like the time was being taken in ServicePointManager.FindServicePoint() which is called creating the WebRequest. I noticed that configuring my target machine with a proper gateway resolved the speed issue however in my case the machine will not always be connected to a larger LAN or internet so I figured out if you set HttpClientHandler.UseProxies to false it skips trying to find a proxy server and it now returns in ~32ms.

Odd that they wouldn't have the FindServicePoint() async but that seemed to be the issue. I thought that with my Uri being a fixed ip i.e. http://192.168.250.1:80/... I would bypass all that stuff but not the case

Upvotes: 1

TheGeneral
TheGeneral

Reputation: 81583

This is likely a problem with a DNS lookup and as pointed out in the comments will likely cache for future calls, if you absolutely need this to not block the UI.

The only solution to this is to offload it (at the expense of a thread pool thread)..

var postTask = await Task.Run(() => _httpClient.PostAsync(Uri, new StringContent(messageString)));

Upvotes: 2

Related Questions