[BUGG] Too many requests being made to Azure Cosmos DB from .NET 6 Web API

User

Im doing many requests to some localhost ports. After 1 minute of running, I start getting this error:

"HttpRequestException: Only one usage of each socket address (protocol/network address/port) is normally permitted. (127.0.0.1:8082)"

And by checking on the event viewer, I found this:

Category: Microsoft.EntityFrameworkCore.Query EventId: 10100 SpanId: cd97008abd8bf70a TraceId: ef9daf484a41559452f6ca1039813c2b ParentId: 0000000000000000 ConnectionId: 0HN0V72URSTLU RequestId: 0HN0V72URSTLU:00000002 RequestPath: /_blazor TransportConnectionId: nJ2ZqdQ7z_L2gXkJeAikzw An exception occurred while iterating over the results of a query for context type ‘OpenBullet2.Core.ApplicationDbContext’. System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see DbContext Lifetime, Configuration, and Initialization - EF Core | Microsoft Learn. at Microsoft.EntityFrameworkCore.Infrastructure.Internal.ConcurrencyDetector.EnterCriticalSection() at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync() Exception: System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see DbContext Lifetime, Configuration, and Initialization - EF Core | Microsoft Learn. at Microsoft.EntityFrameworkCore.Infrastructure.Internal.ConcurrencyDetector.EnterCriticalSection() at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()

How can I fix this? Is there any update or thoughts already about it?

This is chatGPT thougts

The error you’re encountering indicates that you’re attempting to use the same instance of the DbContext from multiple threads concurrently, which is not supported in Entity Framework Core.

To fix this issue, you should ensure that each thread or request has its own instance of the DbContext. In a multi-threaded or multi-request environment, it’s crucial to use a new DbContext instance for each operation to avoid conflicts.

Here are some suggestions:

  1. Use Dependency Injection (DI): If you’re using ASP.NET Core, consider using dependency injection to inject a new instance of the DbContext into your service or controller. ASP.NET Core’s dependency injection system can manage the lifetime of your DbContext.Example using DI in ASP.NET Core:
public class YourService
{
    private readonly ApplicationDbContext _dbContext;

    public YourService(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task YourMethod()
    {
        // Use _dbContext here
    }
}

Manually Create DbContext: If you’re not in an ASP.NET Core environment or want more control, manually create a new instance of DbContext for each thread or request.Example:

using (var dbContext = new ApplicationDbContext())
{
    // Use dbContext here
}

Use async and await Correctly: Ensure that you are using async and await correctly, especially when working with asynchronous operations. Avoid blocking on asynchronous code using .Result or .Wait().Example:

public async Task YourMethod()
{
    // Use await when calling asynchronous methods
    var result = await _dbContext.YourAsyncMethod();
}

Handle the DbContext Lifetime Correctly: If you are manually managing the lifetime of your DbContext, make sure to dispose of it when you’re done with it. The using statement is helpful for this.Example:

using (var dbContext = new ApplicationDbContext())
{
    // Use dbContext here
} // dbContext is automatically disposed at the end of the using block

By ensuring that each thread or request has its own DbContext instance and properly managing the lifetime of the context, you should be able to avoid the “A second operation was started on this context instance before a previous operation completed” error.

@Ruri Check about this please.