
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.
