Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

c# - 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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...