WebApi Core项目调试正在挂起在等待客户端上。

时间:2018-12-11 02:48:42

标签: c# asynchronous asp.net-web-api asp.net-core async-await

我有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);
        }

    }
}

在启动过程中,浏览器打开,然后打开FORM1。执行该行时,单击button1调试器将挂起:

  

HttpResponseMessage响应=等待   client.GetAsync(“ api / ValuesController”);

挂起的原因可能是什么?

谢谢。

1 个答案:

答案 0 :(得分:5)

您正在通过在任务上调用.Wait()来死锁主线程。您需要像这样一直一直等待任务完成:

private async void button1_Click(object sender, EventArgs e)
{
    await TestAutentication();
    Console.ReadKey();
}

关于async void注释,通常它们是代码气味,应避免使用,但是当用于事件处理程序时,可以。

参考: Should I avoid 'async void' event handlers?