如何在使用task . whenall()时允许所有任务完成
本文关键字:许所 任务 whenall task | 更新日期: 2023-09-27 18:13:29
似乎把Task.WhenAll()
放在try-catch
块不工作。代码应该上传所有的图像到ftp,但似乎如果一个上传失败(例如,图像文件在另一个进程中打开),整个uploadTasks
将停止,counts
为空。
private async Task Upload(Ftp ftpHost)
{
var images = GetFileInfo() // will get a List<FileInfo>
var uploadTasks = images.Where(fi => fi.Exists).Select(async fi =>
{
var ret = await ftp.Upload(fi,_cancellationTokenSource.Token);
fi.Delete();
return ret;
});
IEnumerable<int> counts = new List<int>();
try
{
counts = await Task.WhenAll(uploadTasks);
}
catch
{
//ignore to allow all upload complete
}
var uploadedOrderFileByteCount = counts.Sum();
var uploadedOrderFileCount = counts.Count();
}
除了空catch块通常不是一个好主意(尝试捕获ftp上传可能特别抛出的异常)这一事实之外,如果这就是您想要做的,那么最简单的方法是在操作本身内部捕获,类似于下面的代码。
var uploadTasks = images.Where(fi => fi.Exists).Select(async fi =>
{
try
{
var ret = await ftp.Upload(fi,_cancellationTokenSource.Token);
fi.Delete();
return ret;
} catch {
// again, please don't do this...
return 0;
}
});
IEnumerable<int> counts = new List<int>();
try
{
counts = await Task.WhenAll(uploadTasks);
}
catch
{
// Something bad happened, don't just ignore it
}