WebClient()可以同时下载多个字符串吗?

时间:2010-04-24 16:34:32

标签: c# .net wpf webclient

我的意思是我可以做这样的事情:

  var client = new WebClient(); 

  var result = client.DownloadString(string("http://example.com/add.php");

  var result2 = client.DownloadString(string("http://example.com/notadd.php"));

像100个url一样的paralel?

1 个答案:

答案 0 :(得分:2)

在.NET 4.0中,最简单的方法是使用ParallelExtensionsExtras的AsycCache和DownloadStringTask扩展方法。事实上,example for this code涵盖了您的具体情况:

public sealed class HtmlAsyncCache : AsyncCache<Uri, string>
{
    public HtmlAsyncCache() : 
        base(uri => new WebClient().DownloadStringTask(uri)) { }
}

...

HtmlAsyncCache cache = new HtmlAsyncCache();

var page1 = cache.GetValue(new Uri(“http://msdn.microsoft.com/pfxteam”));
var page2 = cache.GetValue(new Uri(“http://msdn.com/concurrency”));
var page3 = cache.GetValue(new Uri(“http://www.microsoft.com”)); 

Task.Factory.ContinueWhenAll(
    new [] { page1, page2, page3 }, completedPages =>
{
    … // use the downloaded pages here
});

有关详细信息,请参阅here