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");
}
EDIT: just found a solution… call
req.Abort()before the end of theusingblock. Not very elegant, but it works… So the code becomes:Try disposing theHttpWebResponseinstead:It should dispose the
NetworkStreamas well.