3

我很难使用 HttpClient 将我在 4.0 中创建的以下代码转换为 4.5。

根据我的理解,我猜如果我收到异步请求,我是否在 GUI 线程本身创建多个 Web 请求而不阻塞 GUI。

如何在 4.5 中使用 HttpClient 将以下代码转换为异步

// This is what called when button is clicked

Task t3 = new Task(SpawnTask);
t3.Start();


//if noofthreads are less 50 then GUI is woking fine.. if number increases then takes much time for repaint.. 
//where as other softwares are working without any problem even if the threads are more     than 500!! in  the same system 
public void SpawnTask()
{
    try
    {
         ParallelOptions po = new ParallelOptions();
         po.CancellationToken = cts.Token;
         po.MaxDegreeOfParallelism = noofthreads;
         Parallel.ForEach(
         urls,
         po,
         url => checkpl(url));
     }
     catch (Exception ex)
     {

     }

 }


  public void checkpl(string url)
  {
     try
     {
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
         request.Timeout = 60*1000;
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         string stext = "";
         using (BufferedStream buffer = new BufferedStream(response.GetResponseStream()))
          {
            using (StreamReader reader = new StreamReader(buffer))
            {
                stext = reader.ReadToEnd();
            }
      }
      response.Close();
   if (stext .IndexOf("domainname.com") != -1)
      {
          tfound = tfound  + 1;
          string lext = "Total Found : "+tfound.ToString();
          label3.BeginInvoke(new InvokeDelegate(UpdateLabel), ltext);
          slist.Add(url);

          textBox2.BeginInvoke(new InvokeDelegate4(UpdateText), "Working Url " + url);

      }
 }
    catch (Exception ex)
    {       
    }
 }
4

1 回答 1

3

由于您使用的是 .NET 4.5,因此您可以使用 newasyncawait关键字。这是它可能的样子。

private async void YourButton_Click(object sender, EventArgs args)
{
    YourButton.Enabled = false;
    try
    {
      var tasks = new List<Task>();
      foreach (string url in Urls)
      {
        tasks.Add(CheckAsync(url));
      }
      await TaskEx.WhenAll(tasks);
    }
    finally
    {
      YourButton.Enabled = true;
    }
}

private async Task CheckAsync(string url)
{
    bool found = await UrlResponseContainsAsync(url, "domainname.com");
    if (found)
    {
        slist.Add(url);
        label3.Text = "Total Found: " + slist.Count.ToString();
        textbox2.Text = "Working Url " + url;
    }
}

private async Task<bool> UrlResponseContainsAsync(string url, string find)
{
    var request = WebRequest.Create(url);
    request.Timeout = 60 * 1000;
    using (WebResponse response = await request.GetResponseAsync())
    {
        using (var buffer = new BufferedStream(response.GetResponseStream()))
        using (var reader = new StreamReader(buffer))
        {
            string text = reader.ReadToEnd();
            return text.Contains(find);
        }
    }
}
于 2013-10-04T14:47:20.877 回答