簡體   English   中英

同時調用Multi-WebApi會導致在先前的操作完成之前在此上下文中啟動第二個操作

[英]Call Multi-WebApi at same time cause A second operation started on this context before a previous operation completed

同時調用多重API(從dbContext查詢)時發生

 A second operation started on this context before a previous operation completed.

.Net Core 2.2(僅適用於Web API)

微軟SQL 2014

Vue(前端)

-嘗試在連接字符串中添加MultipleActiveResultSets = True

-嘗試在瞬態模式下使dbContext

仍然失敗

startUp.cs

services.AddDbContext<BaseContext>(options => options
.UseLazyLoadingProxies()
.EnableSensitiveDataLogging()
.UseSqlServer(connStr), ServiceLifetime.Transient);

Api初始化

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly BaseContext _context;

        public ValuesController(BaseContext test) { _context = test; }
// POST api/values
        [HttpPost]
        public ActionResult Post(SearchCodeFileRequest search, int page = 1)
        {
            var result = GetList(search, page);

            return Ok(result);
        }

api使用的函數

private List<TestModel> GetList(SearchCodeFileRequest search, int page = 1)
        {
                var data = _context.Category.Include(a => a.CategoryParentCategoryItem).Where(a => !a.IsDeleted);

                var list = data.Select(a => new TestModel
                               {
                                   id = a.GID,
                                   parentName =
                                       a.ItemCategory == null ? "" : a.ItemCategory.ItemDescription,
                                   desc = a.ItemDescription,
                                   itemCode = a.ItemCode,
                                   locked = a.Lock,
                                   childrenCnt = a.CategoryParentCategoryItem == null
                                       ? 0
                                       : a.CategoryParentCategoryItem.Count(c => !c.IsDeleted)
                               })
                               .ToList();
                return list;
        }

jwt的前端呼叫API

test() {
      const api = '/api/values';
      this.$http
        .post(api, this.search)
    },

created() {
    this.test();
    this.test();
    this.test();
    this.test();
  },

有時發生

An unhandled exception was thrown by the application. System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext, however instance members are not guaranteed to be thread-safe.

不知道根本原因,每次Api調用??時,它已經創建了一個新的數據庫實例。

非常感謝您的幫助!

在方法內創建和布置上下文,而不是使用全局上下文。

using (var _context = new context()) 
{
  _context.Category.Include(a => a.CategoryParentCategoryItem).Where(a => !a.IsDeleted);
}

正如Terrencep所說,我更改代碼。 但仍然彈出相同的錯誤

private List<CodeFileListModel> GetList(SearchCodeFileRequest search, int page = 1)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                                               .SetBasePath(Directory.GetCurrentDirectory())
                                               .AddJsonFile("appsettings.Development.json")
                                               .Build();

            var builder = new DbContextOptionsBuilder<BaseContext>();
            var connectionString = configuration.GetSection("DbSetting").GetSection("ConnectionString").Value;
            builder.UseSqlServer(connectionString);

            using (var contextText = new BaseContext(builder.Options))
            {
                var data = contextText.Category.Include(a => a.CategoryParentCategoryItem).Where(a => !a.IsDeleted);

                var list = data.Select(a => new CodeFileListModel
                               {
                                   id = a.GID,
                                   parentName =
                                       a.ItemCategory == null ? "" : a.ItemCategory.ItemDescription,
                                   desc = a.ItemDescription,
                                   itemCode = a.ItemCode,
                                   locked = a.Lock,
                                   childrenCnt = a.CategoryParentCategoryItem == null
                                       ? 0
                                       : a.CategoryParentCategoryItem.Count(c => !c.IsDeleted)
                               })
                               .ToList();

                return list;
            }
        }

謝謝大家,我已經發現問題出在中間件上,該中間件也訪問dbContext,並且共享同一個dbcontext確實很多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM