gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:36 25 4
gpt4 key购买 nike

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

  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 一样并行?

最佳答案

在 .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了解更多详情。

关于c# - WebClient() 可以同时下载多个字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2705251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com