在 ASP.NET 中将 ObjectContext 存储在线程静态变量中是否安全?
我读过,我应该在 HttpContext.Current
中存储 ObjectContext
,以便在调用的不同服务/存储库之间共享我的 ObjectContext
一个请求。我想知道在 static
类变量上使用带有 [ThreadStatic]
属性的 ObjectContext
是否安全。这样做安全吗?每个请求都在自己的线程中处理吗?
I've read that I should store an ObjectContext
in HttpContext.Current
in order to share my ObjectContext
across different services/repositories that are called in a request. I'm wondering if it is safe to use an ObjectContext
with the [ThreadStatic]
attribute on a static
class variable instead. Is that a safe thing to do? Is each request processed in its own thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,同一个线程中可以有多个请求,更重要的是,一个请求可以在多个线程中处理。这称为线程敏捷性,当您将内容存储在线程静态变量而不是上下文中时,您会遇到问题:当 ASP.NET 在同一请求期间从一个线程移动到另一个线程时 ,HttpContext 仍然可以访问,但是线程静态变量却不能访问。
一些包含更多信息的链接:
No, there can be multiple requests in the same thread and, more importantly, one request can be processed in multiple threads. This is called thread agility, and you will run into problems when you store stuff in thread-static variables instead of the Context: When ASP.NET moves from one thread to another during the same request, the HttpContext is still accessible, but the thread-static variable is not.
Some links with further information:
使用单个线程来处理请求,并且在现有请求完成之前,其他请求不会使用该线程。但是,您需要考虑如何确保即使发生异常情况也可以处理上下文对象中的项目。一旦线程完成一个请求(无论出于何种原因),它将被重新用于处理其他请求。您不希望前一个请求的状态泄漏到下一个请求中。
A single thread is used to process a request and no other request will use that thread until the existing request is complete. However you need to consider how you make sure that items in the your context object are disposed of even when there is something exceptional happening. Once the thread is finished with a request for what ever reason it will be re-used to process other requests. You don't want state from a previous request leaking into the next.