关于C# 异步执行 Task.WhenAll

情景:在ui中对图片做批量的旋转,等待表格刷新的时间太长了,于是希望并行去解决。

思路:可以用C#自带的Parallel或则Task解决图像旋转的任务,但是注意不要在并行线程中访问UI的资源,等图像旋转结束后,再在UI中刷新;通过Task.WhenAll检测所有图像都旋转完成。

 private async void rightRotate90_Click(object sender, EventArgs e)
 {
     if (this.dgStudentInfo != null && this.dgStudentInfo.SelectedRows.Count > 0)
     {
         FrmProcessingWait dialog = new FrmProcessingWait("图像旋转中,请等待...");
         dialog.Show();
         dialog.Refresh();

         var tasks = new List<Task>();

         for (int i = 0; i < this.dgStudentInfo.SelectedRows.Count; i++)
         {
             DataGridViewRow currentRow = this.dgStudentInfo.SelectedRows[i];
             YBrainTaskFile current_selectFile = currentRow.Tag as YBrainTaskFile;

             if (current_selectFile != null)
             {
                 // 启动并行任务
                 var task = Task.Run(() =>
                 {
                     try
                     {
                         if (!string.IsNullOrEmpty(current_selectFile.firstPage))
                         {
                             Rotate90Img(current_selectFile.firstPage);
                         }

                         if (!string.IsNullOrEmpty(current_selectFile.secondPage))
                         {
                             Rotate90Img(current_selectFile.secondPage);
                         }
                     }
                     catch (Exception ex)
                     {
                         // 可选:记录日志
                     }
                 });

                 tasks.Add(task);
             }
         }

         // 等待所有任务完成
         await Task.WhenAll(tasks);

         // 回到 UI 线程更新图片
         foreach (DataGridViewRow row in this.dgStudentInfo.SelectedRows)
         {
             YBrainTaskFile file = row.Tag as YBrainTaskFile;
             if (file != null)
             {
                 if (!string.IsNullOrEmpty(file.firstPage))
                 {
                     using (FileStream stream = new FileStream(file.firstPage, FileMode.Open))
                     {
                         Image img = Image.FromStream(stream);
                         picImage.Image = img;
                     }
                 }

                 if (!string.IsNullOrEmpty(file.secondPage))
                 {
                     using (FileStream stream = new FileStream(file.secondPage, FileMode.Open))
                     {
                         Image img = Image.FromStream(stream);
                         picSecond.Image = img;
                     }
                 }
             }
         }

         dialog.Dispose();
     }
 }

 

posted @ 2025-07-09 17:17  Wind_Swing_Dunn  阅读(7)  评论(0)    收藏  举报