Can WebClient() download more than one string at the same time?

萝らか妹 提交于 2019-12-11 04:04:47

问题


I mean can I do something like this:

  var client = new WebClient(); 

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

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

in paralel like for 100 url's ?


回答1:


In .NET 4.0, the simplest way is to use the ParallelExtensionsExtras's AsycCache along with the DownloadStringTask extension method. In fact, the example for this code covers your exact scenario:

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
});

See here for more details.



来源:https://stackoverflow.com/questions/2705251/can-webclient-download-more-than-one-string-at-the-same-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!