试图将我的程序的一部分转换为异步 http 客户端调用。取出部分代码(如下)进行测试。基本上是一个非阻塞的异步按钮(据我所知)SendAsync()。它不应该阻塞 UI 线程,对吗?由于我目前看不到的原因,它仍然会阻止它。
我花了两天时间试图找出问题所在。我实现了非阻塞文件写入日志和电子邮件发送功能,它们工作正常。
有人可以指出我做错了什么吗?
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;
}
}
}