Home > OS >  How to stop winforms app from freezing when I make an api call
How to stop winforms app from freezing when I make an api call

Time:12-06

Here is my web request function

static public async Task<JObject> SendCommand(string token, string url, string type)
{
    WebRequest request = WebRequest.Create(url);
    request.Method = type;
    request.ContentType = "application/json";
    request.Headers.Add("Authorization", "Bearer "   token);
    request.Headers.Add("Host", "api.ws.sonos.com");
    request.ContentLength = 0;

    try
    {
        WebResponse response = await request.GetResponseAsync();

        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            string responseContent = reader.ReadToEnd();

            JObject adResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(responseContent);

            return adResponse;
        }
    }
    catch (WebException webException)
    {
        if (webException.Response != null)
        {
            using (StreamReader reader = new StreamReader(webException.Response.GetResponseStream()))
            {
                string responseContent = reader.ReadToEnd();
                return Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(responseContent);
                //return responseContent;
            }
        }
    }

    return null;
}

And this is my form code:

public partial class TestForm : Form
{
    public TestForm()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Console.WriteLine("ok");
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        MessageBox.Show(Api.SendCommand("MyToken", "https://api.ws.sonos.com/control/api/v1/households/Sonos_I3ZEerR2PZBHAi46pLY8w1vAxR.s9H8In1EVjyMMLljBPk7/groups", "GET").Result.ToString());
    }
}

I ran this function in the console and it worked perfectly but when I run it in my Winforms app everything freezes, I've moved the function from a console app to a Winforms class library and then into the Winforms project itself but that didn't help, how can I fix this?

CodePudding user response:

If you await your Api.SendCommand() it should prevent your winforms app from freezing.

private async void button1_Click(object sender, EventArgs e)
{
    var result = await Api.SendCommand("MyToken", 
        "https://api.ws.sonos.com/control/api/v1/households/Sonos_I3ZEerR2PZBHAi46pLY8w1vAxR.s9H8In1EVjyMMLljBPk7/groups",
        "GET");

    MessageBox.Show(result.ToString());
}
  • Related