本文介绍了可以WebClient的()下载多个字符串在同一时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在像100网址paralel?

in paralel like for 100 url's ?

推荐答案

在.NET 4.0中,最简单的方法是使用的的AsycCache随着DownloadStringTask扩展方法。事实上,例如这个code 包括您的具体情况:

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

请参阅这里了解更多详情。

这篇关于可以WebClient的()下载多个字符串在同一时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 06:08