下面的代码上传文件到ftp并返回文件和字节数,如何使其并行运行

本文关键字:文件 字节数 运行 并行 何使其 返回 ftp 代码 | 更新日期: 2023-09-27 18:12:18

  private async Task Upload(Ftp ftpHost)
     {
         //var assetImages is List<FileInfo>  
         var uploadedOrderFileByteCount = 0;
         var uploadedOrderFileCount = 0;
         foreach (var fi in assetImages.Where(fi => fi.Exists))
         {
             uploadedOrderFileCount++;
             var count = ftp.Upload(fi);
             uploadedOrderFileByteCount += await count;
             fi.Delete();
         }
     }

下面的代码上传文件到ftp并返回文件和字节数,如何使其并行运行

您可以通过使用Task.WhenAll:

来实现简单的async并行。
private async Task Upload(Ftp ftpHost)
{
   //var assetImages is List<FileInfo>  
   var uploadTasks = assetImages.Where(fi => fi.Exists).Select(async fi =>
   {
      var ret = await ftp.Upload(fi);
      fi.Delete();
      return ret;
   }).ToArray();
   var counts = await Task.WhenAll(uploadTasks);
   var uploadedOrderFileByteCount = counts.Sum();
   var uploadedOrderFileCount = counts.Count();
}