1

下面的代码按预期工作,但我不确定我会使用最优雅的代码。

 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,当我在父母继续时会被处置。但是,如果我使用 a finalTask.Wait(),则 UI 会冻结。对我上面的内容有更好的解决方案吗?

4

1 回答 1

3

你可以避免第一次使用。在这两种情况下都使用上下文,如果您确定第二个任务将始终被执行,请在最后释放它,否则添加一些额外的代码以确保您的上下文总是被释放。

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();
 });

}
于 2013-08-09T15:28:55.277 回答