【发布时间】:2020-04-06 07:40:22
【问题描述】:
我正在使用 Parallel.ForEach 将 C# 中的多个文件从谷歌存储桶下载到文件夹位置。我正在使用重试逻辑,因此它可以在下载过程中文件下载失败的情况下重试下载文件。如何为Parallel.ForEach 循环中的每个文件或每个线程应用重试逻辑。
Parallel.ForEach(listFiles, objectName =>
{
retryCount = 0;
countOfFiles++;
downloadSuccess = false;
bucketFileName = Path.GetFileName(objectName.Name);
guidFolderPath = tempFolderLocation + "\\" + bucketFileName;
while (retryCount < retryCountInput && downloadSuccess == false)
{
try
{
FileStream fs = new FileStream(guidFolderPath, FileMode.Create, FileAccess.Write, FileShare.Write);
using (fs)
{
storage.DownloadObjectAsync(bucketName, objectName.Name, fs, option, cancellationToken, progress).Wait();
}
}
catch (Exception ex)
{
Console.WriteLine("Exception occured while downloading file: " + ex.ToString());
Thread.Sleep(RetryInterval(retryCount, minBackoffTimeSpan, maxBackoffTimeSpan, deltaBackoffTimeSpan));
retryCount++;
}
}
}
【问题讨论】:
-
看来您已经创建了自己的重试机制。不行吗?
-
如果您在下载后将 downloadSuccess 设置为 true,您的代码可能会工作
-
您不应该将
Parallel.ForEach()用于IO 绑定工作。创建一个任务列表并await Task.WhenAll(list)他们。Thread.Sleep(做到了这一切。您正在阻塞线程池线程。 -
跨线程共享
bucketFileName感觉就像是灾难的秘诀。
标签: c# concurrency parallel.foreach retry-logic