炫意html5
最早CSS3和HTML5移动技术网站之一

NetCore Websocket 数据库上下文被两个线程访问

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>();
}

炫意HTML5 » NetCore Websocket 数据库上下文被两个线程访问

Java基础教程Android基础教程