c#中有多个HttpWebRequest

本文关键字:HttpWebRequest | 更新日期: 2023-09-27 18:25:17

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

问题是,如果我运行一个从0到列表计数的普通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
}

c#中有多个HttpWebRequest

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

  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;