Reputation: 5022
I have a UI thread which enables the user to set certain properties of an entity.
I also have worker threads which will automatically modify properties of an entity that, importantly, the user does not have access to.
Would it be safe to have different DbContexts
per thread and just depend on my programming to always avoid modifying the same property and then attempting to SaveChanges()
on a context which has the same entity modified in different ways?
Or is there a safer way of doing this, i.e. a way in which it will be possible for a programmer to some day change the code such that the same property is modified from two different contexts safely? Or is this latter situation simply one where the programmer has to be careful/refactor around?
Upvotes: 4
Views: 2455
Reputation: 28355
There are three ways to resolve the concurrency issues in the multi-threading environment:
locks
for an item being edited - no one else can edit the item already being edited. This is very hard to implement approach, and this way is quite bad from performance view - all the editing threads are waiting for a single writer, and just wasting the system resources.lock
some operations, but not all.Entity framework authors encourage you to use the optimistic way in your app. The simple use-case is to add RowVersion
or similar-named property to your model, and catch the DBUpdatedException
during the UPDATE
.
You can use the Code-First
solution, like this:
[Timestamp]
public byte[] RowVersion { get; set; }
or Database-First
solution (add column with database editor):
After that, your code for a simple case will be like:
using (var context = new SchoolDBEntities())
{
try
{
context.Entry(student1WithUser2).State = EntityState.Modified;
context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
Console.WriteLine("Optimistic Concurrency exception occured");
}
}
As I understood, you have to examine some properties of your data source, so I suggest you to read a great article regarding such use-cases (it is about an MVC-application, but I'm sure that you can manage out the main idea).
You can also find several articles regarding concurrency in Entity Framework on MSDN:
DbPropertyValues
to access complex propertiesAs you can see, this situation relies completely on a developer side, and you have a great amount of patterns you may choose to resolve you concurrent issues by yourself.
Upvotes: 2