多线程webRequest问题

时间:2019-03-19 16:25:02

标签: c# multithreading httpwebrequest

我在处理多线程Web请求时遇到一些困难,我想使用以下代码一次对一个URL执行100个GET请求:

static void Main(string[] args)
    {
        for (int i = 0; i <= 100; i++)
        {
            Console.WriteLine("RUN TASK: " + i);
            Task.Run(() =>
            {
                makeRequest();
            });
        }
        Console.Read();

    }
    public static void makeRequest()
    {
        string html = string.Empty;
        string url = @"https://192.168.205.50/api/v1/status";
        Console.WriteLine("GET ON:" + url);

        ServicePointManager.UseNagleAlgorithm = true;
        ServicePointManager.Expect100Continue = true;
        ServicePointManager.CheckCertificateRevocationList = true;
        ServicePointManager.DefaultConnectionLimit = 1000;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ServicePoint.ConnectionLimit = 1000;
        ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream stream = response.GetResponseStream())

        using (StreamReader reader = new StreamReader(stream))
        {
            Console.WriteLine("Got response");
            html = reader.ReadToEnd();
        }
    }

该网址的睡眠时间为30秒:代码仅每1秒打开一次网址,而不是一次打开100。

2 个答案:

答案 0 :(得分:1)

个人而言,当我不得不执行大量HTTP请求时,我会使用async / await并执行类似的操作

var stringsToCall = /* list/enumerable of uris */
HttpClient client = new HttpClient(); // Don't declare this locally, and only use an instance. Leaving it here for simplicity.
return await Task.WhenAll(urlsToCall.Select(url => client.GetAsync(url)));

这将为我们的HTTP调用创建一系列任务,并允许我们一次发送许多任务。 如果您有兴趣,请阅读async / await。

答案 1 :(得分:-1)

该方法未标记为异步,因此您正在执行请求并等待响应

相关问题