简体   繁体   English

ASP.NET控制器+实体框架上下文=线程安全吗?

[英]ASP.NET Controllers + Entity Framework Context = thread safe?

All, 所有,

I am writing code that looks like: 我正在写看起来像这样的代码:

public class UserController : AuthenticatedController
{

    private MunicipalContext db = new MunicipalContext();

    // GET: Users/Edit/5
    public ActionResult Edit(int? id)
    {
        //Do stuff with db.Users
    }

    // Other action methods that do stuff with db.Users
}

Coming from a Java background, this feels like Servlets and instance fields and is starting to raise that buzzing feeling in the back of my head. 来自Java背景,感觉就像Servlet和实例字段,并且开始在我的脑海中引发这种嗡嗡声。

Am I going to run into thread safety issues? 我会遇到线程安全问题吗?

Each controller will be created once per request, they are not singletons. 每个控制器将为每个请求创建一次,它们不是单例。 No instance member is shared between threads. 线程之间没有共享实例成员。

So the answer is no, there is no threading issue with your code, each time a new request to an action of your UserController is made a new UserController and a new MunicipalContext are created. 因此,答案是否定的,每当对UserController的操作提出新请求时,代码就不会出现线程问题,即会创建新的UserController和新的MunicipalContext

A side note: remember to Dispose() your MunicipalContext instance when is no longer used. 附带说明:记住在不再使用Dispose()您的MunicipalContext实例时。 More info here . 更多信息在这里

You don't have any thread-safety issues, but typically you would use a slightly different pattern with ASP.NET MVC where the context is injected into the controller using IoC to achieve a context-per-request pattern 您没有任何线程安全问题,但是通常您会在ASP.NET MVC中使用略有不同的模式,其中使用IoC将上下文注入到控制器中以实现每个请求的上下文模式

The problems would arise if your controller consume some services which are also doing database acccess - if you don't share the context between them you can get some odd and/or incorrect behaviour. 如果您的控制器使用了某些服务,这些服务也正在执行数据库访问,则会出现问题-如果您不共享它们之间的上下文,则可能会得到一些奇怪的和/或错误的行为。

The IoC container can then perform the dispose on the context after the request is processed; 然后,IoC容器可以在处理请求之后在上下文上执行处理; how you actually do this depends on whether you are using traditional ASP.NET (via a HttpModule) or Owin (middleware component) 实际操作方式取决于您使用的是传统的ASP.NET(通过HttpModule)还是Owin(中间件组件)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM