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

现在许多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

转载于:https://www.cnblogs.com/since87/p/6081973.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值