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

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

.net - Am I able to reuse a HttpWebRequest?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...