I'm writing classes to support domain model CRUD operations and I would like to try multi threading to get the best performance out of my code.
My workflow is as follows:
- Create a Project
- Create a historical record for the Project
- Extract tasks from the Project and create each Task
My code:
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
}
}
When using the parameters BMSContext (DbContext), validation and project will I be at risk of locking exceptions?
(if yes) How do I prevent against this?
and finally, is it wise to protect against my variables (DbContext in particular) in this way or is there a better architecture/pattern that would work more efficiently?