Consider this scenario:
The repository:
public void Save(object entity) {
lock (static object) {
context.Add(entity);
context.SaveChanges();
}
}
The application:
//somewhere
new Thread(() => Repository.Save(entity)).Start()
//...
This "action" occurs several times. Randomly the db context raises an AccessViolationException
during saving operation (unhandled exception despite the try-catch o.0).
I have already read that this kind of exception can be caused by a concurrent access on the context object.
The question is: why does this exception occur in my case? Note that the lock should ensure the thread-safe access. How can I resolve this problem?
I have an idea... I think that the context.SaveChanges
is not "blocking". When a thread commits the saving another thread enters in the Save
method causes a concurrency access...