0%

多线程执行DbContext

A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913

问题出现场景

多线程操作EFCore 获取数据库上下文姿势不对;以下是正确姿势!

需求

使用 ef core v5.0.9 对数据库表新增数据。

多线程操作EFCore

步骤1:设置程序线程池最大化

1
2
3
4
5
6
7
public static void Main(string[] args)
{
int maxWorkerThreads, maxIoThreads;
ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIoThreads);

CreateHostBuilder(args).Build().Run();
}

有利于程序中线程创建速度加快。

步骤2:OrderingContext 数据上下文注入为瞬时

1
2
3
4
5
6
7
8
9
10
public void ConfigureServices(IServiceCollection services)
services.AddDbContext<OrderingContext>(options =>
{
if (Startup.EfLoggerFactory != null)
options.UseLoggerFactory(Startup.EfLoggerFactory);
options.UseSqlServer(configuration["OrderCommandDBConfig:ConnectionString"]);//, builder => builder.EnableRetryOnFailure()
},
ServiceLifetime.Transient,
ServiceLifetime.Transient
).AddUnitOfWork<OrderingContext>();

注入DbContext声明周期为, ServiceLifetime.Transient , 其他Ioc容器也设置为这个瞬时状态;

步骤3:仓储注入IServiceProvider

1
2
3
4
5
6
7
8
9
public class OrderRepository : Repository<Order, OrderingContext>, IOrderRepository
{
private IServiceProvider _serviceProvider;


public OrderRepository(OrderingContext context, IServiceProvider serviceProvider) : base(context)
{
_serviceProvider = serviceProvider;
}

业务代码调用数据库上下文, 从_serviceProvider获取数据库上下文实例

1
2
3
4
using (var ct = _serviceProvider.GetService<OrderingContext>())
{
...业务代码...
}
-------------本文结束感谢您的阅读-------------
本网站所有内容均收集于互联网或自己创作, 方便于网友与自己学习交流,如有侵权,请留言,立即处理

欢迎关注我的其它发布渠道

本文标题:多线程执行DbContext

文章作者:peter

发布时间:2022年07月19日 - 10:07

最后更新:2022年07月28日 - 11:07

原始链接:https://www.123zhibei.xyz/article/2667f274.html

许可协议: 转载请保留原文链接及作者。