public class ProductService
{
personal readonly IDbContextFactory _factory;
public ProductService(IDbContextFactory manufacturing facility)
=> _factory = manufacturing facility;
public async Activity GetByIdAsync(int id)
{
await utilizing var context = await _factory.CreateDbContextAsync();
return await context.Merchandise.FindAsync(id);
}
public async Activity 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 are going to have their very own context, connection, and change-tracking data, and there might be no mutable state, so that you don’t must implement thread synchronization in both of those strategies.
Contemplate the next code that executes a learn operation and an replace operation in two separate duties.
public static async Activity RunMethodsInParallelAsync(ProductService productService)
{
Activity readTask = productService.GetByIdAsync(1);
Activity updateTask = productService.UpdateStockQuantityAsync(3, 5);
await Activity.WhenAll(readTask, updateTask);
Product? product = await readTask;
}
The Activity.WhenAll technique runs the 2 duties in parallel and waits till each have completed. The rationale this method is thread-safe, and won’t create concurrency errors, is that every of those two strategies creates its personal DbContext occasion internally. Subsequently the learn operation and the replace operation use unbiased DbContext situations.
