HttpWebResponse GetResponseStream 挂在 Dispose 中
我正在使用 HttpWebResponse.GetResponseStream 访问互联网广播流,并希望从响应流中读取一些数据,然后断开连接。但是,我总是无限期地挂在流的 Dispose 上。下面的单元测试将显示“清理网络流...”,但永远不会显示“完成”。这是为什么呢?我是否应该通过不去处理我的网络流来解决这个问题?
[Test]
public void CanStreamMP3Radio()
{
string url = @"http://radio.reaper.fm/stream/";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
int total = 0;
byte[] buffer = new byte[1024];
using(var networkStream = resp.GetResponseStream())
{
do
{
int bytesRead = networkStream.Read(buffer, 0, buffer.Length);
Console.WriteLine("{0} bytesRead", bytesRead);
total += bytesRead;
} while (total < 16384);
Console.WriteLine("Cleaning up networkStream...");
}
Console.WriteLine("Finished");
}
I am using HttpWebResponse.GetResponseStream
to access an internet radio stream, and want to read some data from the response stream, and then disconnect. However, I always hang indefinitely on the Dispose of the stream. The unit test below will display "Cleaning up networkStream...", but never get to "Finished". Why is this? And should I fix it by just not bothering to Dispose of my networkStream?
[Test]
public void CanStreamMP3Radio()
{
string url = @"http://radio.reaper.fm/stream/";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
int total = 0;
byte[] buffer = new byte[1024];
using(var networkStream = resp.GetResponseStream())
{
do
{
int bytesRead = networkStream.Read(buffer, 0, buffer.Length);
Console.WriteLine("{0} bytesRead", bytesRead);
total += bytesRead;
} while (total < 16384);
Console.WriteLine("Cleaning up networkStream...");
}
Console.WriteLine("Finished");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:刚刚找到了一个解决方案...在
using
块结束之前调用req.Abort()
。不是很优雅,但它可以工作......所以代码变成:尝试处理HttpWebResponse
相反:它应该处理NetworkStream
也是如此。EDIT: just found a solution... call
req.Abort()
before the end of theusing
block. Not very elegant, but it works... So the code becomes:Try disposing theHttpWebResponse
instead:It should dispose theNetworkStream
as well.