Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# working with Entity Framework in a multi threaded server

What is the best practice for working with entity framework in a multi threaded server? I'm using entity framework ObjectContext to manage all my database actions, now I know this context isn't thread safe, so for now when I need to use it to perform some db actions I surround it with lock statement to be safe. Is this how I should do it??

like image 321
Eyal Avatar asked Feb 23 '12 15:02

Eyal


2 Answers

Some quick advices for Entity Framework in a multi-threaded environment:

  • Don't use a unique context with locks (no singleton pattern)
  • Provide stateless services (you need to instantiate and dispose one context per request)
  • Shorten the context lifetime as much as possible
  • Do implement a concurrency-control system. Optimistic concurrency can be easily implemented with Entity Framework (how-to). This will ensure you don't overwrite changes in the DB when you use an entity that is not up-to-date

I'm a bit confused, I thought that using one context is good because it does some catching I believe, so when I'm dealing with the same entity in consecutive requests it be much faster to use the same context then creating a new context every time. So why does it good to use it like this if It slower and still not thread safe?

You could use only one context, but it's strongly discouraged unless you really know what you are doing.

I see two main problems that often happen with such an approach:

  1. you'll use a lot of memory as your context will never be disposed and all manipulated entities will be cached in memory (each entity that appears in the result of a query is cached).

  2. you'll face lots of concurrency issues if you modify you data from another program/context. For example, if you modify something directly in your database and the associated entity was already cached in your unique context object, then your context won't ever know about the modification that was made directly in the database. You'll work with a cached entity that is not up-to-date, and trust me, it'll lead to hard-to-find-and-fix issues.

Also don't worry about performances of using multiple contexts: the overhead of creating/disposing a new context per request is almost insignificant in 90% of use cases. Remember that creating a new context does not necessarily create a new connection to the database (as the database generally uses a connection pool).

like image 108
ken2k Avatar answered Sep 21 '22 20:09

ken2k


Is this how I should do it??

No. At a minimum, use a context per thread but I strongly encourage you to think of a context as unit of work, and thus use a context per unit of work per thread.

It's up to you to define "unit of work" for your application. But don't use lock to use a context across multiple threads. It doesn't scale.

like image 20
jason Avatar answered Sep 19 '22 20:09

jason