如何在C#中为HttpWebRequest设置ConnectionLimit?

时间:2016-11-08 01:49:09

标签: c# connection httpwebrequest

我正在开发 MultiThreadingDownloader 项目。所以我需要使用不同的范围同时向多个URL发送请求。我知道WebRequest.ServicePoint.ConnectionLimit设置了连接的限制。但是,设置一次还是我们需要在每个部分请求中设置它都足够了吗?

我目前正在使用它:

    HttpWebResponse SendRequest(string url, int from, int to)
    {
        HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
        req.AddRange(from, to);

        //This is done in every method call. 
        //Does it makes N * 20 for N request or stay the same?
        req.ServicePoint.ConnectionLimit = 20;

        return req.GetResponse() as HttpWebResponse;
    }
    void Start()
    {
        SendRequest(0, 140, url);
        SendRequest(141, 281, url);
        SendRequest(282, 422, url);
        //...20 times call...
    }

我很好奇,如果我将它用于同一个网址,它是否有效?

我的意思是:

    bool limitset = false;

    HttpWebResponse SendRequest(string url, int from, int to)
    {
        HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
        req.AddRange(from, to);

        //This is done in every method call. 
        //Does it makes N * 20 for N request or stay the same?
        if (!limitset)
        {
            req.ServicePoint.ConnectionLimit = 20;
            limitset = true;
        }

        return req.GetResponse() as HttpWebResponse;
    }

0 个答案:

没有答案