下面的代码按预期工作,但是我不确定这是我使用的最优雅的代码。
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
parent 继续的话,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();
});
}
关于c# - 避免在后台任务仍在运行时处理DbContext的更优雅的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18149896/