实体框架线程安全 [英] Entity Framework Thread Safety

查看:154
本文介绍了实体框架线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文对象由实体框架生成的不是线程安全的。

如果我使用两个单独的实体环境中,每个线程(并调用的SaveChanges()每个) - 将这个是线程安全的。

  //此方法是从多个线程同时呼吁
公共无效IncrementProperty()
{
   VAR语境=新MyEntities();   context.SomeObject.SomeIntProperty ++;
   context.SaveChanges();
}

我相信实体框架范围内实现了某种反变量这使在上下文中的当前值是否新鲜与否的轨道。


  1. 随着code以上 - ?我还需要周围的增量锁定/调用SaveChanges
  2. - 从单独的线程调用
  3. 如果是这样,什么是preferred方式在这个简单的场景来完成呢?


解决方案

更​​是一个线程在一个单一的实体框架范围内运营不是线程安全的。

情况下为每个线程的一个单独的实例是线程安全的。只要执行的每个线程都有自己的EF上下文的情况下,你将被罚款。

在你的榜样,您可能会调用code从任意数量的线程同时,每个将自己的上下文中愉快地工作。

不过,我建议实施一个'使用'块这个如下:

  //此方法是从多个线程同时呼吁
公共无效IncrementProperty()
{
   使用(VAR上下文=新MyEntities())
   {
      context.SomeObject.SomeIntProperty ++;
      context.SaveChanges();
   }
}

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?

解决方案

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

这篇关于实体框架线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆