2

Trying to convert part of my program into asynchronous http client call. Took out part of code (which is below) to test. Basically an async'ed button with non-blocking (should be to my knowledge) SendAsync(). It should not block UI thread, am I correct? It still blocks it for a reason I cannot currently see.

I've spent last 2 days trying to figure out whats wrong. I implemented non-blocking file write logging and email send features and they work correctly.

Could someone point out what am I doing wrong please?

private async void button2_Click(object sender, EventArgs e)
    {
    NetworkCredential differentCredToPass = new NetworkCredential("user", "*****", "domain");
    WebProxy wcProxy = new WebProxy("1.1.1.1", 8080);
    wcProxy.UseDefaultCredentials = false;
    wcProxy.Credentials = differentCredToPass;
    var httpHandler = new HttpClientHandler();
    httpHandler.UseProxy = true;
    httpHandler.UseDefaultCredentials = false;
    httpHandler.Proxy = wcProxy;
    using(HttpClient httpClient = new HttpClient(httpHandler) )
        {
        try
            {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://cisco.Com");
            HttpResponseMessage response = await httpClient.SendAsync(request);
            textBox1.AppendText(response.StatusCode.ToString() + Environment.NewLine);
            }
        catch (Exception ex)
            {
            textBox1.AppendText(ex.Message.ToString() + Environment.NewLine);
            throw;
            }
        }
    }
T-series
  • 25
  • 1
  • 5
  • It appears as though you're running this on the UI thread (`button2_Click`), and since you write something to a UI control (`textBox1`), it has to block until it receives a response. If you want it to not block the UI, use a `BackgroundWorker` or otherwise get a thread from another thread pool, and update the textbox in a callback. – Heretic Monkey May 07 '19 at 20:29
  • I moved it to separate function: `public async Task send_Request()` and calling it from button with `string a = await send_Request();`, also removed all referenced to textbox, it still blocks. – T-series May 07 '19 at 20:41

1 Answers1

4

non-blocking (should be to my knowledge) SendAsync()

Well, yes and no. Unfortunately, for historical reasons, SendAsync is not purely asynchronous. Specifically, it does DNS lookup and proxy resolution synchronously. So, to make this fully nonblocking, you would need to wrap that call in a Task.Run:

HttpResponseMessage response = await Task.Run(() => httpClient.SendAsync(request));
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810