c# - Concurrency access with Entity Framework -


i m developing signalr application communicates database. manage database using entity framework 6.

i'd implement scheduled task, deleting records in given table.

the problem task not running on main thread of application. so, if task removes record while main thread trying read same record, application crashes.

i m managing database context way: using (var dbcontext = new databasecontext()) //code , remove record... dbcontext.savechanges();

which best solution avoid concurrency problems ? should force scheduled task run on main thread ? if yes, how can ? or should use transactions locks using transactionscope class ?

edit

scenario: 500ms between each task execution

execution 1 task called first time => new dbcontext instance => record => delete record => savechanges...

in meantime, task called again.

execution 2 task called second time => new dbcontext instance (as first task still running, 2 dbcontext objects alive) => record => delete record => savechanges crashes because has done same @ first time.

exception: store update, insert, or delete statement affected unexpected number of rows (0). entities may have been modified or deleted since entities loaded.

thanks


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -