• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

.NET Core Entity Framework Core 多线程使用Context报错问题

武飞扬头像
Hugo_Hoo
帮助1

本文主要介绍Entity Framework Core在ASP.NET Core中,多个请求中使用同一个context问题,Entity Framework Core上下文(context)不能在多线程中使用,多个请求其实就是多个线程。报错信息:InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()。
引用EF Core的版本:

项目ASP.Net Core版本:ASP.Net Core 2.0

报错信息:

InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
问题原因:

EF Core的Context两个线程同时使用会报该异常; 同一请求中的两个线程,或两个请求。

解决方法:

在Controller中context的中字段不要使用静态的。例如:

private readonly MyDbContext _context; //not static
public MyController(MyDbContext context) {
_context = context;
}
并且在Startup类中ConfigureServices()中配置Context时,要使用如下方法配置:

services.AddTransient();

services.AddDbContext(ServiceLifetime.Transient);
上述配置在每次请求时,创建EF Core Context上下文件,则不会出现多个线程使用同一个Context问题。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfjaabi
系列文章
更多 icon
同类精品
更多 icon
继续加载