Skip to content

OutOfMemoryException causes subsequent InvalidOperationException using AddDbContextPool #22802

Closed as not planned

Description

@cornem

My service executes jobs that communicate with a SQL server database. Every job uses its own IServiceScope. The other day one of my jobs tried to load more records from the database than it could handle, causing a System.OutOfMemoryException. Subsequently, every job failed with System.InvalidOperationException: A second operation started on this context before a previous operation completed.

The context was configured with AddDbContextPool.

Code

services.AddDbContextPool<SqlServerExchangeDbContext>(b =>
{
    b.EnableDetailedErrors();
    b.EnableSensitiveDataLogging();

    b.UseSqlServer(context.Configuration.GetConnectionString("exchange"), options =>
    {
        options.EnableRetryOnFailure();
        options.MigrationsHistoryTable("__EFMigrationsHistoryExchange");
    });
});

Jobs are executed by a queue processor that uses a new IServiceScope per job.

try
{
    using var scope = _serviceProvider.CreateScope();
    var worker = (IExchangeWorker)scope.ServiceProvider.GetRequiredService(job.Type);
    await worker.ExecuteAsync().ConfigureAwait(false);
}
catch (Exception x)
{
    _logger.LogError(x, "An error occurred processing job '{job}'.", job.Name);
}

Stack traces

First exception thrown:

System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at System.Threading.AsyncLocalValueMap.MultiElementAsyncLocalValueMap.Set(IAsyncLocal key, Object value, Boolean treatNullValueAsNonexistent)
   at System.Threading.ExecutionContext.SetLocalValue(IAsyncLocal local, Object newValue, Boolean needChangeNotifications)
   at System.Threading.AsyncLocal`1.set_Value(T value)
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()

Subsequent exceptions:

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. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()

Provider and version information

EF Core version: 3.1.8
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: netcoreapp3.1
Operating system: Windows Server 2016 Datacenter
IDE: Visual Studio 2019 16.7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions