The context objects generated by Entity Framework are not thread-safe.
What if I use two separate entity contexts, one for each thread (and call SaveChanges()
on each) - will this be thread-safe?
// this method is called from several threads concurrently public void IncrementProperty() { var context = new MyEntities(); context.SomeObject.SomeIntProperty++; context.SaveChanges(); }
I believe entity framework context implements some sort of 'counter' variable which keeps track of whether the current values in the context are fresh or not.
Popular Answer. Entity Framework is not thread-safe. An MVC controller is instantiated per request. Thus if you use one DbContext per request, you're safe as long as you don't manually spawn threads in your controller actions (which you shouldn't do anyway).
Using Atomic Variable Using an atomic variable is another way to achieve thread-safety in java. When variables are shared by multiple threads, the atomic variable ensures that threads don't crash into each other.
Usually, objects that are read-only are thread-safe. Many objects that are not read-only are able to have data accesses (read-only) occur with multiple threads without issue, if the object is not modified in the middle.
thread-safety or thread-safe code in Java refers to code that can safely be utilized or shared in concurrent or multi-threading environment and they will behave as expected.
More that one thread operating on a single Entity Framework context is not thread safe.
A separate instance of context for each thread is thread-safe. As long as each thread of execution has its own instance of EF context you will be fine.
In your example, you may call that code from any number of threads concurrently and each will be happily working with its own context.
However, I would suggest implementing a 'using' block for this as follows:
// this method is called from several threads concurrently public void IncrementProperty() { using (var context = new MyEntities()) { context.SomeObject.SomeIntProperty++; context.SaveChanges(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With