我想确保如果在并行循环中抛出期望,则继续任务不会发生
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/