EF4 ObjectContext.SaveChanges 线程安全吗?
我正在通过实体框架 4 访问我的数据库。
我有一个服务器侦听端口,等待一些消息。当消息到来时,它会被转换为表行,并且应该插入到数据库中。但是,可以同时发送多条消息。对于每条消息,我创建一个任务(来自 TPL)并异步执行它。
其中每个任务都会创建一个 ObjectContext 实例,创建相应实体类的对象(表示 DB 中的表),将数据插入到 ObjectContext 中,然后调用 SaveChanges 方法。
因此每个线程创建了自己的ObjectContext。 ObjectContext 的实例可以影响 ObjectContext 的任何其他实例吗? 这种情况会有副作用吗?
(请注意,插入的数据不会产生任何引用完整性错误)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的情况下,事务完整性由数据库(SQL Server)而不是实体框架保证。由于每个线程都有自己的上下文,因此您不必担心每个上下文的
SaveChanges()
会干扰另一个线程。ObjectContext
的一个实例不能影响另一个实例。您可能会遇到这样一种情况:SaveChanges()
修改数据库的方式会导致不同上下文上的后续SaveChanges()
失败。但这是设计使然,也是 SQL Server 强制执行其约束的结果。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 oneSaveChanges()
modifies the database in a way that causes a subsequentSaveChanges()
on a different context to fail. But this is by design and, again, is a result of SQL Server enforcing its constraints.数据上下文通常不是线程安全的;但因为它们都是独立的(每个请求),所以这不是问题。
过于简单化的答案是“不”,因为上下文是不相关的。但是,与数据库对话的任何内容都可能具有边缘条件,具体取决于您在 SaveChanges 之前运行的查询,以及是否有任何结果是幻像或不可重复读取,或者是否有任何内容正在更新数据是否也已被另一个请求更新,或者对不同的请求进行两次插入,单独可以,但组合起来违反唯一约束,等等。
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.