1

I have solution with 2 projects: Asp.Net WebApi Core and WinForms. I am going to consume services from WinForm.

Changed Solution Properties to startup multiple projects: 1st WebApi then WinForm (main form is FORM1).

Now, I have simple code like below:

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

    }
}

During startup browser opens and then FORM1. Clicking on button1 debugger is hanging when executing the line:

HttpResponseMessage response = await client.GetAsync("api/ValuesController");

What could be the reason for hanging?

Thanks in advance.

Tim
  • 459
  • 1
  • 4
  • 20
  • what do you mean by _"hanging"_? Exception? Detach? – vasily.sib Dec 11 '18 at 02:50
  • "...hanging..." - this information is not really helpful. It does not say what exactly did not work, i.e. did you get any error messages anywhere, did you try to debug the issue to make sure that it actually does the intended thing. – jazb Dec 11 '18 at 02:51
  • No any error. I even can not click on button1 again. – Tim Dec 11 '18 at 02:54
  • Are you calling `Console.ReadKey();` from WinForms application? Even though this wil throw a `InvalidOperationException` for "normal" WinForms app, what is your desired behavior? Ok, I will call `AllocConsole();` method from `kernel32.dll` to add console window to my app and get rid of this exception, but now your window will be blocked/freezed/unresponsible until user focus on console window and press any key. Extremly bad application design. – vasily.sib Dec 11 '18 at 05:07

1 Answers1

5

You are deadlocking your main thread by calling .Wait() on the task. You need to await the task all the way up the stack like so:

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

Regarding async void remark, they are normally a code smell and should be avoided, but when used for an event handler it is ok.

Reference: Should I avoid 'async void' event handlers?

Nathan Werry
  • 876
  • 7
  • 18