【发布时间】: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你自己知道你可能做错了 -
在控制台中 .. 完美运行 - 这里的工作方式和那里一样,只是控制台程序 显然没有做任何其他事情 当它的代码正在执行时