c# - 当父任务抛出异常时停止继续任务

标签 c# multithreading task-parallel-library

我想确保如果在并行循环中抛出期望,则继续任务不会发生

 var parent = tf.StartNew(() =>

    Parallel.ForEach(QuestionsLangConstants.questionLangs.Values, (i, state) =>
          {
             try
               {
                 qrepo.UploadQuestions(QWorkBook.Worksheets[i.QSheet],
                 QWorkBook.Worksheets[i.QTranslationSheet], i, prog);
               }
             catch (Exception ex)
               {

                 context.Dispose();
                 state.Break();
                //make sure the execution fails  
               }
          }));

var finalTast = parent.ContinueWith(i =>
            {
                if (context != null)
                {
                    DialogResult result = 
     MessageBox.Show("Do You Want to Commit the Questions?", "Save to DB",
      MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

                    if (result.Equals(DialogResult.OK))
                    {
                       //Do Stuff here
                    }
                    else
                    {
                        return;
                    }
                }
            });

最佳答案

您需要使用ContinueWith overload接受 TaskContinuationOptions 并允许执行冒泡

 var parent = tf.StartNew(() =>

    Parallel.ForEach(QuestionsLangConstants.questionLangs.Values, (i, state) =>
          {
             try
               {
                 qrepo.UploadQuestions(QWorkBook.Worksheets[i.QSheet],
                 QWorkBook.Worksheets[i.QTranslationSheet], i, prog);
               }
             catch (Exception ex)
               {

                 context.Dispose();
                 state.Break();
                //make sure the execution fails  
                throw; //<-- This line was added to stop the continuation task.
               }
          }));

var finalTast = parent.ContinueWith(i =>
            {
               //...
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

关于c# - 当父任务抛出异常时停止继续任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18235363/

相关文章:

c# - 如何在Windows C#中以多个连续模式插入字符串

c# - 如何解析XML文件

objective-c - Objective-C 之外有什么类似于 Grand Central Dispatch 的东西吗?

java - java中的并发队列消耗之谜

c# - AsParallel() 或异步/等待

c# - 需要说明等待任务的方法

c# - 我如何能够更改类外的私有(private)只读数组内的值?

c# - 我可以检测对象是否调用了 GC.SuppressFinalize 吗?

java - 如果上一个任务未完成,如何不启动 ScheduledExecutorService 任务

.net - 在 TPL 中复制队列