多任务并行执行WebClient作为任务(TPL)

时间:2012-11-22 04:36:37

标签: c# enums task-parallel-library webclient

我正在测试IWebDriver vs WebClient的并行执行。 (如果存在性能差异以及它有多大)

在我设法这样做之前,我遇到了简单的WebClient-并行调用问题。

似乎没有被执行,我确实在AgilityPacDocExtraction上设置了制动点 在WebClient.DownloadString(URL)

的特定行

但程序退出 而不是调试Step Into可以显示yeald字符串。

计划是采取单一方法来采取所有必要的行动, 通过每个动作的“模式”选择器, 然后使用一个简单的foreach来迭代所有可用的Enum values - 模式

主要的做法:

   static void Main(string[] args)
   {
        EnumForEach<Action>(Execute);
        Task.WaitAll();
   }
   public static void EnumForEach<Mode>(Action<Mode> Exec)
   {

            foreach (Mode mode in Enum.GetValues(typeof(Mode)))
            {
                Mode Curr = mode;

                Task.Factory.StartNew(() => Exec(Curr) );
            }

   }

模式/动作选择器

    enum Action
    {
        Act1, Act2
    }

实际执行

    static  BrowsresFactory.IeEngine IeNgn = new BrowsresFactory.IeEngin();
    static string 
        FlNm = Environment.CurrentDirectory,
        URL = "",
        TmpHtm ="";


   static void Execute(Action Exc)
   {


        switch (Exc)
        {
            case Action.Act1:
                break;

            case Action.Act2:
                URL  = "UrlofUrChoise here...";
                FlNm += "\\TempHtm.htm";
                TmpHtm = IeNgn.AgilityPacDocExtraction(URL).GetElementbyId("Dv_Main").InnerHtml;
                File.WriteAllText(FlNm, TmpHtm);
                break;

        }
     }

持有WebClientIWebDriver(通过selenium)的课程不包含在这里,因此在这篇文章中不会占用更多空间,而且现在也不会相关。

class BrowsresFactory
{
    public class IeEngine
{

    private WebClient WC = new WebClient();
    private string tmpExtractedPageValue = "";
    private HtmlAgilityPack.HtmlDocument retAglPacHtmDoc = new HtmlAgilityPack.HtmlDocument();

    public HtmlAgilityPack.HtmlDocument AgilityPacDocExtraction(string URL)
    {
                WC.Encoding = Encoding.GetEncoding("UTF-8");
                tmpExtractedPageValue = WC.DownloadString(URL); //<--- tried to break here
                retAglPacHtmDoc.LoadHtml(tmpExtractedPageValue);
                return retAglPacHtmDoc;
    }
}
}

问题是我无法看到文件中的任何内容应该通过从WebClient中提取的值进行更改,而且在调试模式下我无法进入上面代码中注释的行。我在做什么错了?

2 个答案:

答案 0 :(得分:1)

上面的代码中没有定义函数Download(url, htmlDictionary),一个可能的版本是:

private static void Download(string url, ConcurrentDictionary<string, string> htmlDictionary)
{
    using (var webClient = new SmartWebClient())
    {
        htmlDictionary.TryAdd(url, webClient.DownloadString(url));
    }
}

...上面的代码似乎是另一个Stack Overflow帖子的副本。有关参考,请参阅Retrieve a string containing html Document source using Task parallel

答案 1 :(得分:0)

我设法通过使用WebClient来解决问题,我认为这需要的资源少于WebDriver,如果这是真的,那也意味着花费更少的时间。

这是代码:

public void StartEngins()
{
    const string URL_Dollar = "URL_Dollar";
    const string URL_UpdateUsersTimeOut = "URL_UpdateUsersTimeOut";


    var urlList = new Dictionary<string, string>();
    urlList.Add(URL_Dollar, "http://bing.com");
    urlList.Add(URL_UpdateUsersTimeOut, "http://localhost:..../.......aspx");


    var htmlDictionary = new ConcurrentDictionary<string, string>();
    Parallel.ForEach(
                    urlList.Values,
                    new ParallelOptions { MaxDegreeOfParallelism = 20 },
                    url => Download(url, htmlDictionary)
                    );
    foreach (var pair in htmlDictionary)
    {
        ///Process(pair);
        MessageBox.Show(pair.Value);
    }
}

public class SmartWebClient : WebClient
{
    private readonly int maxConcurentConnectionCount;

    public SmartWebClient(int maxConcurentConnectionCount = 20)
    {

        this.maxConcurentConnectionCount = maxConcurentConnectionCount;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var httpWebRequest = (HttpWebRequest)base.GetWebRequest(address);
        if (httpWebRequest == null)
        {
            return null;
        }

        if (maxConcurentConnectionCount != 0)
        {
            httpWebRequest.ServicePoint.ConnectionLimit = maxConcurentConnectionCount;
        }

        return httpWebRequest;
    }

}