Async skips execution in the middle of method

Viewed 232

I am using winforms to scrape JSON data from a website.

The problem is the method doesn't complete and code execution halts at the line // HttpResponseMessage response = await client.PostAsync($"https://ticks.site/api/numberofticks/geticks?ticks={strTicks}", headers);.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TicksProgram
{
    public partial class Scanner : Form
    {
        public Scanner()
        {
            InitializeComponent();

            GetJSON().GetAwaiter().GetResult();
        }

        private async Task GetJSON()
        {
            var client = new HttpClient();

            // headers
            var headers = new FormUrlEncodedContent(new[] {
                new KeyValuePair<string, string>("somestring", "somestring"),
               });


            string strTicks = "5";
            // Get the response.
            HttpResponseMessage response = await client.PostAsync(
                $"https://ticks.site/api/numberofticks/geticks?ticks={strTicks}", headers);
            
            // Get the response content.
            HttpContent responseContent = response.Content;
        }
    }
}

There are no errors.

I am new to async so I am unsure what to do.

1 Answers

You should move your code to the Form_Load event (you can add this via the Windows Forms Designer UI):

private async void Form_Load(object sender, EventArgs e)
{
    await GetJSON();
}

In 99/100 cases, you should not use async void and you should use async Task instead. In the case of WinForms event handlers, you have no other option (you can't change the method signature) and async void is the recommended way to do this.

Related