Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Am I able to reuse a HttpWebRequest?

It seems like the 3rd request to a site causes a operation to time out. It seems like each request creates a new connection, so I want to know if I can reuse a HttpWebRequest by changing the url and getting the request again. The code in question is below. This code checks if a range of urls exists.

    static void storeList(TextWriter sw, string urlTemplate, int start, int end)
    {
        for (int i = start; i < end; i++)
        {
            var url = string.Format(urlTemplate, i);
            var req = (HttpWebRequest)HttpWebRequest.Create(url);
            {
                req.Method = "HEAD";
                tryHttpWebRequest
                {
                    var resp = req.GetResponse();
                    sw.WriteLine(i);
                }
                catch (Exception e)
                {
                }
            }
        }
        sw.Flush();
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
458 views
Welcome To Ask or Share your Answers For Others

1 Answer

You should be ok if you just call Close on your response. You are only allowed so many "open" connections, so the reason it is failing is because it can't open a new connection.

Once you are done with the response, you need to close it... no need to reuse anything.

From the MSDN article:

You must call either the Stream.Close or the HttpWebResponse.Close method to close the response and release the connection for reuse. It is not necessary to call both Stream.Close and HttpWebResponse.Close, but doing so does not cause an error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...