How to execute queries in parallel using EF Core

public class ProductService
{
    private readonly IDbContextFactory _factory;
    public ProductService(IDbContextFactory factory)
        => _factory = factory;
    public async Task GetByIdAsync(int id)
    {
        await using var context = await _factory.CreateDbContextAsync();
        return await context.Products.FindAsync(id);
    }
    public async Task UpdateStockQuantityAsync(int id, int updateQuantity)
    {
        await using var context = await _factory.CreateDbContextAsync();
        var product = await context.Products.FindAsync(id);
        if (product is null) return;
        product.Quantity += updateQuantity;
        await context.SaveChangesAsync();
    }
}

Note that ProductService has two methods, GetByIdAsync and UpdateStockQuantityAsync. An instance of the DbContext class is created locally in each of these methods. Now, suppose you have two threads, T1 and T2, that execute these methods concurrently. That is, thread T1 executes the GetByIdAsync method while thread T2 executes the UpdateStockQuantityAsync method. Because each of these methods is executed in isolation, they will have their own context, connection, and change-tracking information, and there will be no mutable state, so you don’t need to implement thread synchronization in either of these methods.

Consider the following code that executes a read operation and an update operation in two separate tasks.

public static async Task RunMethodsInParallelAsync(ProductService productService)
{
      Task readTask = productService.GetByIdAsync(1);
      Task updateTask = productService.UpdateStockQuantityAsync(3, 5);
      await Task.WhenAll(readTask, updateTask);
      Product? product = await readTask;
 }

The Task.WhenAll method runs the two tasks in parallel and waits until both have finished. The reason this approach is thread-safe, and will not create concurrency errors, is that each of these two methods creates its own DbContext instance internally. Therefore the read operation and the update operation use independent DbContext instances.

Donner Music, make your music with gear
Multi-Function Air Blower: Blowing, suction, extraction, and even inflation

Leave a reply

Please enter your comment!
Please enter your name here