I am developing a SignalR application that communicates with a database. I am managing a database using Entity Framework 6.
I would like to accomplish a scheduled task that will delete some entries in this table.
The problem is that this task is not performed in the main thread of my application. Thus, if this task deletes a record while the main thread is trying to read the same record, the application crashes.
I manage the database context this way: using (var dbContext = new DatabaseContext()) //code to get and remove record... dbContext.saveChanges();
What would be the best solution to avoid concurrency issues? Should I get the scheduled task to work in the main thread? If so, how can I do this? Or should I use transaction locks using the TransactionScope class?
EDIT
Scenario: 500 ms between each task
execution 1 task called for the first time => new instance of dbContext => get record => delete record => save changes> ..
In the meantime, the task is called again.
execution 2 task called a second time => a new instance of dbContext (as the first task is still running, two dbContext objects are alive) => get record => delete record => saveChanges failed because it already did the same for the first time.
Exception: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded.
thanks
Rotan source share