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

时间:2022-12-06 23:43:44

现在许多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”属性。连接的当前状态为已关闭。

  

测试代码

EF DbContext 并发执行时可能出现的问题EF DbContext 并发执行时可能出现的问题
 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