当我调用api时,如何阻止winforms应用程序冻结



这是我的web请求函数

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类库,然后移动到Winorms项目本身,但这无济于事,我该如何解决这个问题?

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

最新更新