2

似乎放入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();
}
4

1 回答 1

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
}
于 2013-05-14T22:47:03.320 回答