seagull
seagull

Reputation: 237

how to allow all task complete when using Task.WhenAll()?

It seems like putting Task.WhenAll() in a try-catch block doesn't work. The code should upload all the images to ftp, but it seems like if one upload fails (for example, the image file is open in another process), the whole uploadTasks will stop, and counts is empty.

    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();
}

Upvotes: 2

Views: 999

Answers (1)

carlosfigueira
carlosfigueira

Reputation: 87238

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
}

Upvotes: 2

Related Questions