gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:55:32 25 4
gpt4 key购买 nike

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

 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com