3.1 C
Canberra
Friday, July 24, 2026

The best way to execute queries in parallel utilizing EF Core



public class ProductService
{
    personal readonly IDbContextFactory _factory;
    public ProductService(IDbContextFactory manufacturing facility)
        => _factory = manufacturing facility;
    public async Process GetByIdAsync(int id)
    {
        await utilizing var context = await _factory.CreateDbContextAsync();
        return await context.Merchandise.FindAsync(id);
    }
    public async Process 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();
    }
}

Observe 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’ve 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 likely be no mutable state, so that you don’t must 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 Process RunMethodsInParallelAsync(ProductService productService)
{
      Process readTask = productService.GetByIdAsync(1);
      Process updateTask = productService.UpdateStockQuantityAsync(3, 5);
      await Process.WhenAll(readTask, updateTask);
      Product? product = await readTask;
 }

The Process.WhenAll technique runs the 2 duties in parallel and waits till each have completed. The explanation this method 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 unbiased DbContext situations.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles