Reputation: 9562
I am accessing my database via Entity Framework 4.
I have a server that listens on a port, awaiting some messages. When a message comes, it is translated into a table row and it should be inserted into the database. However, multiple messages can come at once. For each message I create a Task (from TPL) and execute it asynchronously.
Each of these tasks creates an instance of the ObjectContext, creates an object of the appropriate entity class (represents a table in DB), inserts the data into the ObjectContext, and then calls the SaveChanges method.
Thus each thread created its own ObjectContext. Can an instance of the ObjectContext influence any other instance of the ObjectContext? Would this scenario have any side-effects?
(Note that the data inserted won't create any referential integrity error).
Upvotes: 0
Views: 1307
Reputation: 50825
In your situation transactional integrity is guaranteed by the database (SQL Server) and not Entity Framework. Since each thread has its own context you don't have to worry about each context's SaveChanges()
interfering with another.
One instance of ObjectContext
can not influence another one. You may run into a situation where one SaveChanges()
modifies the database in a way that causes a subsequent SaveChanges()
on a different context to fail. But this is by design and, again, is a result of SQL Server enforcing its constraints.
Upvotes: 5
Reputation: 1062494
A data-context is not usually thread-safe; but because they are all independent (per-request) that is not an issue.
The overly simplistic answer is "no", in that the contexts are unrelated. However, anything talking to the database may have edge conditions, depending on what queries you run before the SaveChanges
, and whether any turn out to be phantom or non-repeatable reads, or if anything is updating data that has also been updated by another request, or doing 2 inserts on different requests that individually would be fine, but in combination violate a unique constraint, etc.
Upvotes: 1