我有一个程序,里面有很多HttpWebRequest
个调用。它为各种流媒体平台(Twitch,Hitbox,Beam,YouTube)提供了大量外部API请求。我的所有要求似乎都很好。
以下是我的一个要求的示例:
private void save_Click(object sender, RoutedEventArgs e)
{
string postUrl = "https://api.twitch.tv/kraken/channels/" + this.channelID;
string postData = "channel[status]=" + Uri.EscapeDataString(status.Text) +
"&channel[game]=" + Uri.EscapeDataString(game.Text);
byte[] postByte = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "PUT";
request.Accept = "application/vnd.twitchtv.v5+json";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postByte.Length;
request.Headers.Add("Authorization", "OAuth " + password.Password);
request.Headers.Add("Client-ID", this.clientID);
request.Timeout = 15000;
try
{
Stream putStream = request.GetRequestStream();
putStream.Write(postByte, 0, postByte.Length);
putStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch (WebException err)
{
MessageBox.Show("Unable to update channel information:\n" + err.Message);
}
}
但是,如果请求失败(例如短暂的互联网打嗝),并且try-catch因超时而响应错误,则会出现问题,因此在重新启动程序之前,将来不会有HttpWebRequests工作。< / p>
只有在超时启动错误捕获时才会发生这种情况。
是否有这种情况发生的原因以及如何解决?
答案 0 :(得分:1)
这很可能是由未正确释放导致锁定的资源引起的。
将您的代码更改为可能在WebException上调用HttpWebRequest上的中止,也可能将HttpWebResponse和putStream包装在using语句中。
private void save_Click(object sender, RoutedEventArgs e)
{
string postUrl = "https://api.twitch.tv/kraken/channels/" + this.channelID;
string postData = "channel[status]=" + Uri.EscapeDataString(status.Text) +
"&channel[game]=" + Uri.EscapeDataString(game.Text);
byte[] postByte = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "PUT";
request.Accept = "application/vnd.twitchtv.v5+json";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postByte.Length;
request.Headers.Add("Authorization", "OAuth " + password.Password);
request.Headers.Add("Client-ID", this.clientID);
request.Timeout = 15000;
try
{
using (Stream putStream = request.GetRequestStream())
{
putStream.Write(postByte, 0, postByte.Length);
using (var response = (HttpWebResponse) request.GetResponse())
{
//assign the response result to a variable else it's getting disposed
}
}
}
catch (WebException err)
{
request.Abort();
MessageBox.Show("Unable to update channel information:\n" + err.Message);
}
}