3

4.0 で作成した以下のコードを HttpClient を使用して 4.5 に変換するのに苦労しています。

私の理解によると、非同期リクエストを取得した場合、GUIをブロックせずにGUIスレッド自体で複数のWebリクエストを作成すると思います。

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 を使用しているため、 newasyncおよびawaitキーワードを使用できます。これがどのように見えるかです。

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 に答える