gpt4 book ai didi

c# - 真正的并行下载

转载 作者:可可西里 更新时间:2023-11-01 10:52:38 25 4
gpt4 key购买 nike

我正在使用这种方法进行并发下载。

public void DownloadConcurrent(Action Method)
{
Action[] methodList = new Action[Concurent_Downloads];

for (int i = 0; i < Concurent_Downloads; i++)
{
methodList[i] = Method;
}

Parallel.Invoke(methodList);
}

我正在尝试同时下载 url,但事件下载次数始终是一个。

就像所有的下载都会调用,但只有一个 url 会开始下载数据,而不是像所有的都会开始进行下载。

我希望所有下载同时并行工作,但无法实现。

更新:该方法使用队列,它正在下载不同的 url,形成队列。

最佳答案

WebClient 的实例成员不是线程安全的,因此请确保在每个操作中都有一个单独的实例。在您展示的方法中,您似乎多次乘以同一个 Action 委托(delegate)。所以你不是在下载不同的网址,你是在多次下载同一个网址。而且由于 WebClient 不是线程安全的,您可能会遇到问题。

这是使用 TPL 并行下载多个 url 的示例:

using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

class Program
{
static void Main()
{
var urls = new[]
{
"http://google.com",
"http://yahoo.com",
"http://stackoverflow.com"
};

var tasks = urls
.Select(url => Task.Factory.StartNew(
state =>
{
using (var client = new WebClient())
{
var u = (string)state;
Console.WriteLine("starting to download {0}", u);
string result = client.DownloadString(u);
Console.WriteLine("finished downloading {0}", u);
}
}, url)
)
.ToArray();

Task.WaitAll(tasks);
}
}

关于c# - 真正的并行下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6716301/

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