使用静态DbContext的缺点是什么 [英] What are the disadvantages of using static DbContext
问题描述
我是Visual Studio的新手.我正在开发MVC Web项目,并且正在使用静态DbContext
.由于用户登录时它不是一个简单的网页,因此他将使用该程序很长时间,并且我希望它能快速运行.使用静态DbContext
有什么缺点?
I am new to Visual Studio. I am developing a MVC web project and I'm using static DbContext
. Because it is not a simple web page when a user sign in, he will use the program for a long time and I want it to be fast. What are the disadvantages of using static DbContext
?
推荐答案
由于DbContext
不是线程安全的,因此如果您的应用程序具有异步操作,则可能会使用DbContext使用多个线程,这可能导致异常.
Since DbContext
is not thread safe, if your application have async action then it's possible to have multiple thread using your DbContext, which can lead to an exception.
另一方面,创建新的DbContext
实例并不意味着打开与DB的新连接. Net Framework应该使用已经在Connection Pool
中打开的连接之一.
On another hand, creating a new DbContext
instance doesn't mean open a new connection to DB. Net Framework should use one of connections already open in Connection Pool
.
如果仅使用一个DbContext
实例并将其锁定以确保线程安全,那么您与DB的连接只有一个.如果您的网站每秒有数百个请求,那么它们都必须排队才能使用唯一的连接.在这种情况下,DbContext对象成为您系统的性能瓶颈.
If you only use one DbContext
instance and lock it for thread safety, so you only have one connection to DB. If your website have hundreds of request per second then all of them have to queue to use the only connection. In that case, DbContext object became the perfomance bottleneck of your system.
使用静态DbContext
实例时,EF中的数据缓存存在很多问题.
And there are tons of problem with data caching in EF when you working with static DbContext
instance.
因此,最好为每个请求创建一个新的DbContext实例-让框架为我们管理连接,不要担心它应该很快.
So, it's better to create a new instance of DbContext for each request - let the framework manage the connection for us and don't worry it should fast.
这篇关于使用静态DbContext的缺点是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!