Reputation: 2910
I want to make sure that the continuation task will not happen if an expection is thrown in the parallel loop
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;
}
}
});
Upvotes: 2
Views: 189
Reputation: 50712
Don't swallow exception, and run continue only for not on faulted
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);
Upvotes: 2
Reputation: 127543
You need to use the ContinueWith overload that takes in TaskContinuationOptions
and allow the execption to bubble up
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);
Upvotes: 2