从父任务引发异常时停止Continuation Task
本文关键字:Continuation Task 异常 任务 | 更新日期: 2023-09-27 18:27:36
如果在并行循环中抛出期望,我想确保继续任务不会发生
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重载来接收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);
不要吞下异常,只对未出现故障的运行continue
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;
}
}));
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;
}
}
}, TaskContinuationOptions.NotOnFaulted);