EF Core中的错误:在此上下文上启动了第二项操作,而之前的操作尚未完成

时间:2018-12-27 16:56:33

标签: asp.net .net asp.net-core entity-framework-core

我的网络api应用出现了奇怪的错误: 在先前的操作完成之前,第二操作在此上下文上开始。不保证任何实例成员都是线程安全的。

我有一个计算用户发薪日并更新其用户休假余额的过程。所以我需要迭代用户并获取其休假余额,然后对每个余额进行更新。我还不知道如何解决此错误。 当我调用包含b的this.SaveAll()时触发的错误

    public async Task<bool> SaveAll()
    {
        return await _context.SaveChangesAsync() > 0;
    }

还将datacontext注入以下代码:

private readonly DataContext _context;
    private readonly IAdminSettingsRepository _settingRepo;
    private readonly IAppRepository _appRepository;
    public PayrollRepository(DataContext context, IAdminSettingsRepository settingRepo, IAppRepository appRepository)
    {
        _context = context;
        _settingRepo = settingRepo;
        _appRepository = appRepository;
    }

过程如下:

public async Task<bool> ProcessPayCalendar(PayCalendar payCalendar)
        {
            List<User> users = payCalendar.Users.ToList();
            SickLeaveEntitlement sickLeaveEntitlement = await _settingRepo.GetSickLeaveEntitlement();
            AnnualLeaveEntitlement annualLeaveEntitlement = await _settingRepo.GetAnnualLeaveEntitlement();
            LongServiceLeaveEntitlement longServiceLeaveEntitlement = await _settingRepo.GetLongServiceLeaveEntitlement();
            DateTime tenYearsAgo = DateTime.Today.AddYears(-10);
            DateTime currentMonth = new DateTime(payCalendar.NextPaymentDate.Year, payCalendar.NextPaymentDate.Month, 1);
            DateTime previousMonth = currentMonth.AddMonths(-1);


            /// begin calculation for leave calendar
            users.ForEach(async user =>
            {
                decimal hoursWorked = this.CalculateWorkingHours(user);
                decimal hourlyRate = this.CalculateHourlyRate(user);
                // create pay day for user
                Payday payday = new Payday();
                payday.UserId = user.Id;
                payday.PayPeriodStart = payCalendar.PayPeriodStartDate;
                payday.PayPeriodEnd = payCalendar.PayPeriodEndDate;
                payday.PaymentDate = payCalendar.NextPaymentDate;
                payday.HoursWorked = hoursWorked;
                payday.SickLeaveAccrual = this.CalculateSickLeaveEntitlement(hoursWorked, sickLeaveEntitlement);
                payday.AnnualLeaveAccrual = this.CalculateAnnualLeaveEntitlement(hoursWorked, annualLeaveEntitlement);
                payday.LongServiceLeaveAccrual = (user.StartDateCurrentAnnualSalary > tenYearsAgo) ? 0m : this.CalculateLongServiceEntitlement(hoursWorked, longServiceLeaveEntitlement);
                payday.SickLeaveAccrualValue = payday.SickLeaveAccrual * hourlyRate;
                payday.AnnualLeaveAccrualValue = payday.AnnualLeaveAccrual * hourlyRate;
                payday.LongServiceLeaveAccrualValue = payday.LongServiceLeaveAccrual * hourlyRate;

                this.Add(payday);

                // do calculation on leave balance 
                // jika leave balance di awal bulan maka lakukan replikasi dr bulan sebelumnya.
                // closebalance menjadi opening balance bulan selanjutnya.
                LeaveBalance sickLeaveBalance = await this.GetUserLeaveBalance(user.Id, sickLeaveEntitlement, "sickLeave");
                if (sickLeaveBalance == null)
                {
                    // sickLeaveBalance =  await this.CreateLeaveBalance(user.Id,sickLeaveEntitlement,"sickLeave",payday.PaymentDate);
                    // sickLeaveBalance.CurrentBalance =+ payday.SickLeaveAccrual ;
                    // sickLeaveBalance.CurrentBalanceValue += payday.SickLeaveAccrualValue;
                    throw new Exception($"Sick Leave balance for user: {user.Username} is not found. Please report this as bug");
                }
                else
                {
                    sickLeaveBalance.CurrentBalance = +payday.SickLeaveAccrual;
                    sickLeaveBalance.CurrentBalanceValue += payday.SickLeaveAccrualValue;
                    sickLeaveBalance.LastUpdate = payday.PaymentDate;
                }

                LeaveBalance annualLeaveBalance = await this.GetUserLeaveBalance(user.Id, annualLeaveEntitlement, "annualLeave");
                if (annualLeaveBalance == null)
                {
                    throw new Exception($"Annual Leave balance for user: {user.Username} is not found. Please report this as bug");
                }
                else
                {
                    annualLeaveBalance.CurrentBalance = +payday.AnnualLeaveAccrual;
                    annualLeaveBalance.CurrentBalanceValue += payday.AnnualLeaveAccrualValue;   
                    annualLeaveBalance.LastUpdate = payday.PaymentDate;

                }
                LeaveBalance longServiceLeaveBalance = await this.GetUserLeaveBalance(user.Id, longServiceLeaveEntitlement, "longServiceLeave");
                if (longServiceLeaveBalance == null)
                {
                    throw new Exception($"Long Service Leave balance for user: {user.Username} is not found. Please report this as bug");
                }
                else
                {
                    longServiceLeaveBalance.CurrentBalance = +payday.LongServiceLeaveAccrual;
                    longServiceLeaveBalance.CurrentBalanceValue += payday.LongServiceLeaveAccrualValue;
                    longServiceLeaveBalance.LastUpdate = payday.PaymentDate;

                }
            });
            return await this.SaveAll();
        }

完整错误:

  

失败:Microsoft.EntityFrameworkCore.Update [10000]         保存上下文类型为“ CRSApp.API.Data.DataContext”的更改时,数据库中发生了异常。         System.InvalidOperationException:在上一个操作完成之前,在此上下文上启动了第二个操作。不保证任何实例成员都是线程安全的。            在Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()            在Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList 1 entriesToSave, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) System.InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe. at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection() at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList 1个条目要保存,CancellationToken取消令牌)中      在Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess,CancellationToken cancelToken)      在Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess,CancellationToken cancelToken)   失败:Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware [1]         执行请求时发生未处理的异常。   System.InvalidOperationException:在上一个操作完成之前,在此上下文上启动了第二个操作。不保证任何实例成员都是线程安全的。      在Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()      在Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList 1 entriesToSave, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at CRSApp.API.Data.PayrollRepository.SaveAll() in E:\CRSApp\crsapp.api\Data\PayrollRepository.cs:line 35 at CRSApp.API.Data.PayrollRepository.ProcessPayCalendar(PayCalendar payCalendar) in E:\CRSApp\crsapp.api\Data\PayrollRepository.cs:line 229 at CRSApp.API.Controllers.Admin.PayrollController.ProcessPayCalendar(PayCalendarParam param) in E:\CRSApp\crsapp.api\Controllers\Admin\PayrollController.cs:line 68 at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at System.Threading.Tasks.ValueTask 1.get_Result()      在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()      在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()      在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext上下文)      在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(状态和下一个,范围和范围,对象和状态,布尔值和isCompleted)处      在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext上下文)      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(状态和下一个,范围和范围,对象和状态,布尔值和已完成)      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()      在Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)      在Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext上下文)      在Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext上下文)      在Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext上下文)      在Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext上下文)

Fyi:我按照下面的说明使用Dotnet Core 2.1.1。

<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.1"/>
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.0" PrivateAssets="All"/>
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="4.0.1"/>
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.1.1"/>
    <PackageReference Include="MailKit" Version="2.0.6"/>
  </ItemGroup>

1 个答案:

答案 0 :(得分:0)

DbContext不是线程安全的

我认为这是ForEach的问题。

 users.ForEach(async user =>
        {
           //....

            LeaveBalance sickLeaveBalance = await this.GetUserLeaveBalance(user.Id,});
           // .....
        });

使用async关键字时,因此将为每个用户异步调用一个动作,因此您的代码执行将类似于以下代码的执行:

foreach(var user in users){
     //without await
     //it's an async method
    DoSomeThingAsync(user); //you called GetUserLeaveBalance in DoSomeThingAsync
}

而且我猜想,GetUserLeaveBalance使用的是DbContext,所以您正在使用DbContext 异步,您将遇到类似这样的错误

  

在此之前,第二个操作在此上下文上开始   完成...

您需要将ForEach更改为类似的内容

foreach(var user in users){
    await DoSomeThingAsync(user); //you called GetUserLeaveBalance in DoSomeThingAsync
}