C#任务并行库第一次慢

时间:2015-03-24 15:39:11

标签: c# multithreading winforms task-parallel-library

尝试并行执行大量HTTP Get请求,每个任务一个。如果我通过Internet Explorer浏览器,他们几乎立即返回,但是当通过任务调用代码时,我第一次关闭它们时,它们需要花费几秒钟才能返回,但是第二次运行它们会像我期望的那样返回。所以要么我做了阻止某事的事情,要么因某种原因线程没有启动?这是我第一次尝试使用TPL。

这是基本的查找类:

public class Lookup
{
  public string Name { get; set; }
  public string URL { get; set; }

  public Lookup(string Name, string URL)
  {
    this.Name = Name;
    this.URL = URL;
  }

  public LookupReturn DoLookup()
  {
    LookupReturn d = new LookupReturn();
    d.Name = this.Name;
    d.URL = this.URL;

    WebRequest wrGETURL;
    wrGETURL = WebRequest.Create(this.URL);

    Stream objStream;
    objStream = wrGETURL.GetResponse().GetResponseStream();

    StreamReader objReader = new StreamReader(objStream);

    string sLine = objReader.ReadToEnd();
    d.Result = sLine;
    return d;
  }
}

返回类型很简单:

public class LookupReturn
{
  public string Name { get; set; }
  public string Result { get; set; }
  public string URL { get; set; }
}

因此尝试并行运行 - 从Winforms GUI进行测试,但最终将在WCF服务中进行测试。

public partial class Form1 : Form
{
  private List<Lookup> Lookups = new List<Lookup>();

  private async void btnRunLookups_Click(object sender, EventArgs e)
  {
    Lookups.Add(new Lookup("Name1", "http://geturl1 "));
    Lookups.Add(new Lookup("Name2", "http://geturl2 ")); 
    // More lookups…  

    int workerThreads, complete;
    ThreadPool.GetMinThreads(out workerThreads, out complete);

    ThreadPool.SetMinThreads(100, complete);

    btnRunLookups.Visible = false;
    List <Task<LookupReturn>> lookupTasks = new List<Task<LookupReturn>>();
    foreach(Lookup dl in Lookups)
    {
      lbLookups.Items.Add("Starting task for " + dl.URL);

      Task<LookupReturn> t = new Task<LookupReturn>(() => dl.DoLookup() );
      lookupTasks.Add(t);
      t.Start();
    }

    //await Task.WhenAny(
    //  Task.WhenAll(lookupTasks.ToArray<Task<LookupReturn>>()), 
    //  Task.Delay(3000)
    //  );

    // This takes a good few seconds the first time
    await Task.WhenAll(lookupTasks.ToArray<Task<LookupReturn>>());

    // Now I need to see which ones completed and returned a result
    foreach (var x in lookupTasks)
    {
      if (x.IsCompleted)
      {
        lbLookups.Items.Add(x.Result);
      }
      else
      {
        // lbLookups.Items.Add("Not finished " + x.Result.Name);
      }
    }
    btnRunLookups.Visible = true;
  }

2 个答案:

答案 0 :(得分:5)

Other people已经注意到HttpWebRequest在第一次请求时可能需要很长时间,因为它正在寻找代理信息。尝试将其Proxy属性设置为null。

wrGETURL = WebRequest.Create(this.URL);
wrGETURL.Proxy = null;

答案 1 :(得分:1)

最有可能的问题是程序在第一次调用GetResponse时正在进行一些首次设置(DNS解析,代理检测等)。特别是代理检测可能需要很长时间。