Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# c中的多个HttpWebRequests_C#_Multithreading - Fatal编程技术网

C# c中的多个HttpWebRequests

C# c中的多个HttpWebRequests,c#,multithreading,C#,Multithreading,我有一个windows窗体应用程序,它从一个文本文件中读取一堆URL~800到列表。然后,应用程序显示所有URL的状态代码 问题是如果我运行一个从0到list count的普通for循环,它会花费很多时间。我需要在不阻塞UI的情况下最大限度地加快进程。下面是我的代码 private async void button1_Click(object sender, EventArgs e) { System.IO.StreamReader file = new System.IO.Stream

我有一个windows窗体应用程序,它从一个文本文件中读取一堆URL~800到列表。然后,应用程序显示所有URL的状态代码

问题是如果我运行一个从0到list count的普通for循环,它会花费很多时间。我需要在不阻塞UI的情况下最大限度地加快进程。下面是我的代码

private async void button1_Click(object sender, EventArgs e)
{
   System.IO.StreamReader file = new System.IO.StreamReader("urls.txt");

        while ((line = file.ReadLine()) != null)
        {
            pages.Add(line);

        }
        file.Close();

      for(int i=0; i<pages.Count; i++)
      {
               HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pages[i]);
                         int code = 0;
                         try
                         {

                             WebResponse response = await request.GetResponseAsync();

                             HttpWebResponse r = (HttpWebResponse)response;

                             code = (int)r.StatusCode;
                         }
                         catch (WebException we)
                         {
                             var r = ((HttpWebResponse)we.Response).StatusCode;
                             code = (int)r;
                         }
       }
  //add the url and status code to a datagridview
}

一种方法是使用任务,这样在开始下一个请求之前,您就不会等待最后一个请求完成

  Task<int> tasks;
  for (int i = 0; i < 10; i++)
  {
    tasks = Task.Run<int>(() =>
      {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pages[i]);
        int code = 0;
        try
        {

          WebResponse response = request.GetResponse();

          HttpWebResponse r = (HttpWebResponse)response;

          code = (int)r.StatusCode;
        }
        catch (WebException we)
        {
          var r = ((HttpWebResponse)we.Response).StatusCode;
          code = (int)r;
        }

        return code;
      }
    );
  }
  await tasks;

使用此选项时,速度没有明显变化。