【发布时间】:2017-08-04 21:39:54
【问题描述】:
我正在下载 100K+ 个文件,并希望以补丁的形式进行,例如一次 100 个文件。
static void Main(string[] args) {
Task.WaitAll(
new Task[]{
RunAsync()
});
}
// each group has 100 attachments.
static async Task RunAsync() {
foreach (var group in groups) {
var tasks = new List<Task>();
foreach (var attachment in group.attachments) {
tasks.Add(DownloadFileAsync(attachment, downloadPath));
}
await Task.WhenAll(tasks);
}
}
static async Task DownloadFileAsync(Attachment attachment, string path) {
using (var client = new HttpClient()) {
using (var fileStream = File.Create(path + attachment.FileName)) {
var downloadedFileStream = await client.GetStreamAsync(attachment.url);
await downloadedFileStream.CopyToAsync(fileStream);
}
}
}
预期 希望它一次下载100个文件,然后再下载下100个;
实际
它同时下载更多。赶紧报错Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host
【问题讨论】:
-
很遗憾它被标记为重复,因为另一个问题使用了截然不同的方法,我很高兴知道为什么 Quentin 使用的方法失败了。
-
我同意;不是重复的。我的猜测是 HttpClient 方法比您希望的更早返回。
-
我在 .NET Core 中使用 Web 服务时遇到了类似的问题。将任务放入队列中,一旦任务完成,从队列中取出并运行任务。你当然应该同步队列。那应该可以。
-
谢谢@MertAkcakaya 将尝试队列方法。
标签: c# async-await