此代码是否会导致锁定异常,我该如何解决?

时间:2015-10-16 13:31:03

标签: c# multithreading entity-framework

我正在编写类来支持域模型CRUD操作,我想尝试使用多线程来获得代码中的最佳性能。

我的工作流程如下:

  1. 创建项目
  2. 为项目创建历史记录
  3. 从项目中提取任务并创建每个任务
  4. 我的代码:

    public class CreateProject : Base.BaseBMSEntityCreate<Project> {
        public CreateProject(BMSContext context, IValidationDictionary validation) : base(context, validation) { }
    
        public override Project Create(Project entity) {
            //create the project
            //set any default values on entity
            //base.Create adds the entity to the DbContext (BMSContext) that was set in constructor
            //and returns the entity
            var project = base.Create(entity);
    
            //create history for the project
            System.Threading.Tasks.Task history = System.Threading.Tasks.Task.Factory.StartNew(() => createHistory(db, validation, project));
    
            //create tasks for the project
            System.Threading.Tasks.Task tasks = System.Threading.Tasks.Task.Factory.StartNew(() => createTasks(db, validation, project));
    
            System.Threading.Tasks.Task.WaitAll(history, tasks);
    
            return project;
        }
    
        private void createTasks(BMSContext db, IValidationDictionary validation, Project project) {
            //in here I will be making use of:
            //1.    context
            //2.    validation
            //3.    project.Tasks
        }
    
        private void createHistory(BMSContext context, IValidationDictionary validation, Project project) {
            //in here I will be making use of:
            //1.    context
            //2.    validation
            //3.    project
        }
    }
    

    当使用参数BMSContext(DbContext)时,验证和项目是否会有锁定异常的风险?

    (如果是)我该如何防止这种情况发生?

    最后,以这种方式保护我的变量(特别是DbContext)是否明智,还是有更好的架构/模式可以更有效地工作?

0 个答案:

没有答案