【问题标题】:How to stop winforms app from freezing when I make an api call当我进行 api 调用时如何阻止 winforms 应用程序冻结
【发布时间】:2022-01-10 17:28:30
【问题描述】:

这是我的网络请求函数

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 类库,然后移动到 Winforms 项目本身,但是没有帮助,我该如何解决这个问题?

【问题讨论】:

  • 冻结是因为它在 UI 线程中运行 - 为避免这种情况,请在单独的线程中运行它,或者使 button1_Click_1 异步并使用 await Api.SendCommand(...)
  • 如果你发现自己这样做.Result你自己知道你可能做错了
  • 在控制台中 .. 完美运行 - 这里的工作方式和那里一样,只是控制台程序 显然没有做任何其他事情 当它的代码正在执行时

标签: c# winforms


【解决方案1】:

如果您等待您的 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());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    相关资源
    最近更新 更多