這是我的網路請求功能
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 應用程式中運行它時一切都凍結了幫助,我該如何解決這個問題?
uj5u.com熱心網友回復:
如果您等待您的 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());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/377590.html
上一篇:記錄員工進出
