Easy methods to execute queries in parallel utilizing EF Core



public class ProductService
{
    non-public readonly IDbContextFactory _factory;
    public ProductService(IDbContextFactory manufacturing facility)
        => _factory = manufacturing facility;
    public async Job GetByIdAsync(int id)
    {
        await utilizing var context = await _factory.CreateDbContextAsync();
        return await context.Merchandise.FindAsync(id);
    }
    public async Job UpdateStockQuantityAsync(int id, int updateQuantity)
    {
        await utilizing var context = await _factory.CreateDbContextAsync();
        var product = await context.Merchandise.FindAsync(id);
        if (product is null) return;
        product.Amount += updateQuantity;
        await context.SaveChangesAsync();
    }
}

Be aware that ProductService has two strategies, GetByIdAsync and UpdateStockQuantityAsync. An occasion of the DbContext class is created domestically in every of those strategies. Now, suppose you might have two threads, T1 and T2, that execute these strategies concurrently. That’s, thread T1 executes the GetByIdAsync technique whereas thread T2 executes the UpdateStockQuantityAsync technique. As a result of every of those strategies is executed in isolation, they may have their very own context, connection, and change-tracking data, and there will probably be no mutable state, so that you don’t have to implement thread synchronization in both of those strategies.

Think about the next code that executes a learn operation and an replace operation in two separate duties.

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

The Job.WhenAll technique runs the 2 duties in parallel and waits till each have completed. The rationale this strategy is thread-safe, and won’t create concurrency errors, is that every of those two strategies creates its personal DbContext occasion internally. Due to this fact the learn operation and the replace operation use impartial DbContext situations.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *