码迷,mamicode.com
首页 > 数据库 > 详细

EF DbContext 并发执行时可能出现的问题

时间:2016-11-20 06:43:02      阅读:798      评论:0      收藏:0      [点我收藏+]

标签:sse   indicator   file   splay   create   test   状态   targe   操作   

现在许多Web项目都使用了IOC的DI注入组件。其中对象的生命周期管理是非常重要的。

有时我们为了提高请求的响应,经常在请求线程中执行多个子线程,然而忽略了EF的DbContext的生命周期管理。

DbContext并非是线程安全的。子线程A和子线程B 可能同时的对同一个DbContext进行操作,从而导致下面的异常(可能随机抛出其中一个)。

所以建议不要共用同一个DbContext.

  

{"已有打开的与此 Command 相关联的 DataReader,必须首先将它关闭。"}

 

“System.InvalidOperationException”类型的异常在 EntityFramework.dll 中发生,但未在用户代码中进行处理

其他信息: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.

 

“System.NullReferenceException”类型的异常在 EntityFramework.dll 中发生,但未在用户代码中进行处理

其他信息: 未将对象引用设置到对象的实例。

  

“System.InvalidOperationException”类型的异常在 System.Data.dll 中发生,但未在用户代码中进行处理

其他信息: 不允许更改“ConnectionString”属性。连接的当前状态为已关闭。

  

测试代码

技术分享
 1 private async void button1_Click(object sender, EventArgs e)
 2 {
 3     try
 4     {
 5         var mydb = new MyDbContext();
 6         var arr = new MyExecuterOfEF[2];
 7         arr[1] = new MyExecuterOfEF(mydb, (db) =>
 8         {
 9             var r = db.Tests.FirstOrDefault();
10         });
11         arr[0] = new MyExecuterOfEF(mydb, (db) =>
12         {
13             var r = db.Tests.FirstOrDefault();
14         });
15        
16         Parallel.ForEach(arr, (myExecute) =>
17         {
18             myExecute.Execute();
19         });
20 
21         MessageBox.Show("结束");
22     }
23     catch (Exception ex)
24     {
25         //MessageBox.Show(ex.ToString());
26         this.textBox1.Text = ex.ToString();
27     }
28 }
View Code

 

Demo

EF DbContext 并发执行时可能出现的问题

标签:sse   indicator   file   splay   create   test   状态   targe   操作   

原文地址:http://www.cnblogs.com/since87/p/6081973.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!