Tim*_*Tim 1 c# asynchronous async-await asp.net-web-api asp.net-core
我有2个项目的解决方案:Asp.Net WebApi Core和WinForms.我将使用WinForm的服务.
更改了解决方案属性以启动多个项目:第一个WebApi然后是WinForm(主窗体是FORM1).
现在,我有如下的简单代码:
private void button1_Click(object sender, EventArgs e)
{
TestAutentication().Wait();
Console.ReadKey();
}
static async Task TestAutentication()
{
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://localhost:53791");
try
{
HttpResponseMessage response = await client.GetAsync("api/ValuesController");
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<string>();
Console.WriteLine("{0}", result);
}
else
{
Console.WriteLine("{0}", response.ReasonPhrase);
}
}
catch (HttpRequestException ex)
{
Console.WriteLine("{0}", ex.Message);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在启动浏览器期间打开然后打开FORM1.在执行该行时单击button1调试器:
HttpResponseMessage response = await client.GetAsync("api/ValuesController");
悬挂的原因是什么?
提前致谢.
您通过调用.Wait()任务使主线程死锁.你需要在堆栈中一直等待任务,如下所示:
private async void button1_Click(object sender, EventArgs e)
{
await TestAutentication();
Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)
关于async void注释,它们通常是代码气味,应该避免,但是当用于事件处理程序时,它是可以的.
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |