gpt4 book ai didi

C# Task.WaitAll 不等待

转载 作者:行者123 更新时间:2023-11-30 14:25:47 25 4
gpt4 key购买 nike

我的目标是从 Amazon Web Services 存储桶下载图像。

我有以下代码功能,可以一次下载多张图片:

public static void DownloadFilesFromAWS(string bucketName, List<string> imageNames)
{
int batchSize = 50;
int maxDownloadMilliseconds = 10000;

List<Task> tasks = new List<Task>();

for (int i = 0; i < imageNames.Count; i++)
{
string imageName = imageNames[i];
Task task = Task.Run(() => GetFile(bucketName, imageName));
tasks.Add(task);
if (tasks.Count > 0 && tasks.Count % batchSize == 0)
{
Task.WaitAll(tasks.ToArray(), maxDownloadMilliseconds);//wait to download
tasks.Clear();
}
}

//if there are any left, wait for them
Task.WaitAll(tasks.ToArray(), maxDownloadMilliseconds);
}

private static void GetFile(string bucketName, string filename)
{
try
{
using (AmazonS3Client awsClient = new AmazonS3Client(Amazon.RegionEndpoint.EUWest1))
{
string key = Path.GetFileName(filename);

GetObjectRequest getObjectRequest = new GetObjectRequest() {
BucketName = bucketName,
Key = key
};

using (GetObjectResponse response = awsClient.GetObject(getObjectRequest))
{
string directory = Path.GetDirectoryName(filename);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}

if (!File.Exists(filename))
{
response.WriteResponseStreamToFile(filename);
}
}
}
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode == "NoSuchKey")
{
return;
}
if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") || amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
// Log AWS invalid credentials
throw new ApplicationException("AWS Invalid Credentials");
}
else
{
// Log generic AWS exception
throw new ApplicationException("AWS Exception: " + amazonS3Exception.Message);
}
}
catch
{
//
}
}

图像的下载一切正常,但 Task.WaitAll 似乎被忽略,其余代码继续执行 - 这意味着我尝试获取当前不存在的文件(因为它们尚未下载)。

我找到了 this回答另一个似乎与我相同的问题。我尝试使用答案来更改我的代码,但它仍然不会等待所有文件下载完毕。

谁能告诉我哪里出错了?

最佳答案

代码的行为符合预期。 Task.WaitAll 会在十秒后返回,即使并非所有文件都已下载,因为您在变量 maxDownloadMilliseconds 中指定了 10 秒(10000 毫秒)的超时。

如果您真的想等待所有下载完成,请调用 Task.WaitAll 而不指定超时。

使用

Task.WaitAll(tasks.ToArray());//wait to download

在两个地方。

要查看有关如何在不对系统施加压力(只有最大并行下载数)的情况下实现并行下载的一些很好的解释,请参阅 How can I limit Parallel.ForEach? 中的答案。

关于C# Task.WaitAll 不等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37251044/

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