一个更优雅的解决方案,可以避免在后台任务仍在运行时处理DbContext
本文关键字:可以避免 后台任务 DbContext 处理 运行时 解决方案 一个 | 更新日期: 2023-09-27 18:26:58
下面的代码按预期工作,但我不确定它是我使用的最优雅的代码。
using (DatabaseContext context = DatabaseContext.CreateContext(_incompleteConnString + prefix + campaignDBPlatform))
Progress prog = new Progress();
TaskFactory tf = new TaskFactory();
var parent = tf.StartNew(() =>
Parallel.ForEach(QuestionsLangConstants.questionLangs.Values, i =>
{
try
{
qrepo.UploadQuestions(QWorkBook.Worksheets[i.QSheet], i, prog);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
})
);
prog.Show();
var finalTask = parent.ContinueWith(i =>
{
using (DatabaseContext context2 = DatabaseContext.CreateContext(_incompleteConnString + prefix + campaignDBPlatform))
{
UploadedQuestionsRepliesRepository uqrepo = new
UploadedQuestionsRepliesRepository(context2);
UploadedQuestionsReplies UQuestions = new UploadedQuestionsReplies() {
Id = (int)uqrepo.getNextSeqValue(),
FileName = "test",
RQType = Questions.QuestionsType.ToString(),
TimeStamp = DateTime.Now
};
uqrepo.Insert(UQuestions);
uqrepo.Save();
}
});
}
如果我不添加context2
,当父级继续时,context
将在我添加时被释放。但是,如果我使用finalTask.Wait()
,UI会冻结。对于我的上述问题,有更好的解决方案吗?
您可以避免第一次使用。在这两种情况下都使用上下文,如果您确信第二个任务将始终执行,请在最后处理它,否则添加一些额外的代码以确保您的上下文始终被处理。
DatabaseContext context2 = DatabaseContext.CreateContext(_incompleteConnString + prefix + campaignDBPlatform)
//Initialize qrepo with the context here??
Progress prog = new Progress();
TaskFactory tf = new TaskFactory();
var parent = tf.StartNew(() =>
Parallel.ForEach(QuestionsLangConstants.questionLangs.Values, i =>
{
try
{
qrepo.UploadQuestions(QWorkBook.Worksheets[i.QSheet], i, prog);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
// Do you really want to continue with the next task after the exception?
}
})
);
prog.Show();
var finalTask = parent.ContinueWith(i =>
{
UploadedQuestionsRepliesRepository uqrepo = new UploadedQuestionsRepliesRepository(context2);
UploadedQuestionsReplies UQuestions = new UploadedQuestionsReplies() {
Id = (int)uqrepo.getNextSeqValue(),
FileName = "test",
RQType = Questions.QuestionsType.ToString(),
TimeStamp = DateTime.Now
};
uqrepo.Insert(UQuestions);
uqrepo.Save();
context2.Dispose();
});
}