我正在使用HttpWebResponse.GetResponseStream
访问互联网广播流,并希望从响应流中读取一些数据,然后断开连接。但是,我总是无限期地挂在流的Dispose上。下面的单元测试将显示“清理networkStream ...”,但永远不会显示“已完成”。为什么是这样?我应该通过不打扰我的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");
}
答案 0 :(得分:3)
编辑:刚刚找到解决方案...在req.Abort()
块结束前调用using
。不是很优雅,但它有效...所以代码变成:
[Test]
public void CanStreamMP3Radio()
{
string url = @"http://radio.reaper.fm/stream/";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
int total = 0;
byte[] buffer = new byte[1024];
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 HttpWebResponse...");
req.Abort();
}
Console.WriteLine("Finished");
}
请尝试处理 HttpWebResponse
:
[Test]
public void CanStreamMP3Radio()
{
string url = @"http://radio.reaper.fm/stream/";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
int total = 0;
byte[] buffer = new byte[1024];
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 HttpWebResponse...");
}
Console.WriteLine("Finished");
}
它也应该处理 NetworkStream
。