public class ProductService
{
personal readonly IDbContextFactory _factory;
public ProductService(IDbContextFactory manufacturing unit)
=> _factory = manufacturing unit;
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 regionally in every of those strategies. Now, suppose you may have two threads, T1 and T2, that execute these strategies concurrently. That’s, thread T1 executes the GetByIdAsync methodology whereas thread T2 executes the UpdateStockQuantityAsync methodology. As a result of every of those strategies is executed in isolation, they’ll have their very own context, connection, and change-tracking data, and there can be no mutable state, so that you don’t have to 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 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 methodology 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 impartial DbContext situations.
