简体   繁体   中英

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.

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

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 ie http://192.168.250.1:80/... I would bypass all that stuff but not the case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM