将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();
}
答案 0 :(得分:2)
除了一个空的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
}