A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext.

 A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. 




在Blazor Server應用中有時候因為撰寫非同步的處理

可能會將原本DB相關存取服務(設置的生命週期:Scoped)

會有此例外發生在某些時候

在asp.net core3.1版本


我們可以藉由

引用命名空間

using Microsoft.Extensions.DependencyInjection;


並且確立只要該服務存取相同的DbContext

有呼叫存取的地方全部都要改為如下寫法

假設該頁有兩隻Service都存取相同DbContext就建議都統一調整

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
using (var scope = this.serviceProvider.CreateScope())
{
    var tmpAAA_Service = scope.ServiceProvider.GetRequiredService<AAA_Service>();
    AAAData = tmpAAA_Service.GetOne();
}

using (var scope = this.serviceProvider.CreateScope())
{
    var tmpBBB_Service = scope.ServiceProvider.GetRequiredService<BBB_Service>();
    List<BBBData> lsBData = tmpBBB_Service.GetAll();
}


其他高手也遇到類似的問題

https://rainmakerho.github.io/2020/09/13/2020020/



留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題