我可以重用HttpWebRequest吗? [英] Am I able to reuse a HttpWebRequest?

查看:70
本文介绍了我可以重用HttpWebRequest吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以重用HttpWebRequest吗?

Am I able to reuse a HttpWebRequest?

似乎对站点的第三个请求导致操作超时。似乎每个请求都创建了一个新的连接,所以我想知道是否可以通过更改url并再次获取请求来重用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();
    }


推荐答案

如果您选择只需在您的回复中致电关闭即可。您只被允许这么多的打开连接,所以失败的原因是因为它无法打开新连接。

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.

来自 MSDN文章


您必须调用Stream.Close
或HttpWebResponse.Close方法,以
关闭响应并释放
连接以供重用。不必同时调用Stream.Close
和HttpWebResponse.Close,但这样做
不会导致错误。

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.

这篇关于我可以重用HttpWebRequest吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆