Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Thread Safety

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.

  1. With the code above - called from separate threads - do I still need to lock around the increment/savechanges?
  2. If so, what is the preferred way to accomplish this in this simple scenario?
like image 329
Harper Avatar asked Dec 15 '10 22:12

Harper


People also ask

Is Entity Framework thread-safe?

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).

How do you ensure thread safety?

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.

Which objects are thread-safe?

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.

What is a thread-safe environment?

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.


1 Answers

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();    } } 
like image 81
Jim Reineri Avatar answered Oct 02 '22 18:10

Jim Reineri