简体   繁体   中英

Return GetResponseStream output to another function , What about respone disposing

i'm working on download manager project and i'm using :

public Stream GetStream(string url)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    return response.GetResponseStream();
}

then use the returned stream as input stream and FileStream as output stream in while statement :

Stream InputStream = GetStream("http://test_url/test.zip");
Stream OutputStream = new FileStream("d:\\test.zip", FileMode.Create, FileAccess.Write));
do
{
    readSize = InputStream.Read(buffer, 0, buffSize);
    OutputStream.Write(buffer, 0, (int)readSize);
}
while (readSize > 0);

when downloading a file over 50MB using my 256kpps connection after about 20 - 30 MB, readSize become 0 without errors

my question is : is there anything wrong with Response object , is it disposed???? or what is the problem?

Thank you in advance, and i'm sorry if i can't explain better.

You aren't disposing your HttpWebRequest / HttpWebResponse objects, which could be causing a problem - there is a built-in limit to the number of concurrent connections to the same server.

You should be doing something like:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using(Stream responseStream = response.GetResponseStream())
    {
        using(Stream outputStream = new FileStream(...))
        {
            responseStream.CopyTo(outputStream);
        }
    }
}

Stream.CopyTo is new in .NET 4.0. If you're using .NET <= 3.x you'll need to write your own .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM