Websocket中使用ReceiveAsync方法读取到数据流后访问Service层,然后做出相应的业务逻辑,但是由于Websocket的生命周期和普通HTTP请求不同,同一个Websocket连接用的是同一个Service层方法,如果一次快速收到一个用户的两条请求,就会提示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.”
Dbcontext注入的为Scoped,Service注入的为Transient
private IServiceProvider _services; 注入
using (var scope = _services.CreateScope())
{
var services = scope.ServiceProvider;
var _userService = services.GetService<IUserService>();
}
妈呀, 我看出dudu1 了
这样做确实可以不报错了,但是每次都会生成一个IUserService实例,没有被释放掉,每一次访问内存占用会增加,怎么样才可以让该实例自动销毁
@叫我昆哥哥: 手动释放呗
是不是 有异步操作DBContext ?这个和 Websocket 没什么关系吧