2

ブロックを入れるTask.WhenAll()try-catchうまくいかないようです。コードはすべての画像を ftp にアップロードする必要がありますが、1 つのアップロードが失敗すると (たとえば、画像ファイルが別のプロセスで開かれている場合)、全体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

Apart from the fact that an empty catch block is often a bad idea (try to catch the exception which the ftp upload can throw especifically), if that's what you want to do, then the easiest way is to catch inside the operation itself, something similar to the code below.

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 に答える