如何在我拨打 api 电话时阻止 winforms 应用程序冻结

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

这是我的网络请求函数

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

这是我的表单代码:

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

我在控制台中 运行 这个函数并且它工作得很好但是当我 运行 它在我的 Winforms 应用程序中时一切都冻结了,我已经将该函数从控制台应用程序移动到 Winforms class 库,然后进入 Winforms 项目本身,但这没有帮助,我该如何解决这个问题?

如果您等待 Api.SendCommand() 它应该可以防止您的 winforms 应用程序冻结。

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