gpt4 book ai didi

c# - HttpWebResponse GetResponseStream 卡在 Dispose 中

转载 作者:行者123 更新时间:2023-11-30 16:30:14 27 4
gpt4 key购买 nike

我正在使用 HttpWebResponse.GetResponseStream 访问互联网广播流,并希望从响应流中读取一些数据,然后断开连接。但是,我总是无限期地卡在流的 Dispose 上。下面的单元测试将显示“Cleaning up networkStream...”,但永远不会显示“Finished”。为什么是这样?我是否应该通过不去处理我的 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");
}

最佳答案

编辑:刚刚找到一个解决方案...在 using block 结束之前调用 req.Abort()。不是很优雅,但它可以工作......所以代码变成:

[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

关于c# - HttpWebResponse GetResponseStream 卡在 Dispose 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5855088/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com