Web 应用程序中的静态变量
我可以在 Web 应用程序中使用静态变量吗? static 的替代品是什么?当我在页面中使用静态变量并且多个用户使用该应用程序时,它会产生冲突数据(不正确的数据)。
使用静态成员有哪些限制?
静态成员在内存中共享吗?
Can I use static variables in my web application ? what are the alternatives to static ? When I use static variables in pages and more than one user use the application, it makes conflict data (incorrect data).
What are the limits of using static members?
Are static members shared in memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑将共享变量存储在 HttpApplication 对象或 Cache 对象中。
但是,如果您尝试单独存储每个用户的值,则应将这些值存储在会话变量中。
Asp.Net 内部的静态变量在 w3svc.exe 进程的内存空间中共享,并且不是线程安全的。应用程序的任何用户都可以访问和修改它们。这可能会导致不必要的修改,除非您围绕这些值的存储编写自己的锁定机制。
您应该尝试如下语法:
存储共享的应用程序范围数据并
基于每个用户存储数据
您可以使用 WebCache 对象将数据存储在具有过期条件的 Web 服务器内存中。其语法类似于: 有关
管理 WebCache 对象的语法的更多信息,请访问:
http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx
Consider storing your shared variables in the HttpApplication object or in the Cache object.
However, if you are trying to store values for each user separately, you should store those values in a Session variable.
Static variables inside Asp.Net are shared in the memory space of the w3svc.exe process and are NOT thread-safe. They can be accessed and modified by any user of the application. This could lead to unwanted modifications, unless you write your own lock mechanism around the storage of those values.
You should try a syntax like:
to store shared application-wide data and
to store data on a per-user basis
You can use the WebCache object to store data in the web server's memory with expiration conditions. Syntax for that looks similar to:
More on the syntax of managing the WebCache object can be found at:
http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx
只是为了补充 @Jeff Fritz 所说的内容,IIS 应用程序会创建一个 AppDomain,您的程序集将在其中加载。就像普通 Windows 应用程序的规则一样,如果诸如
...之类的类,则每个 AppDomain 中只有一个
Something.SomeString
属性可用。 W3SVC 进程管理 AppDomain,但不能保证线程安全(因为 AppDomain 可以服务多个请求)。如果您使用只读静态属性,则可能没问题(例如读取配置值)。如果您要创建在请求的生命周期内发生变化的可变属性,那么最好使用此处其他问题中详细介绍的存储机制之一。Just to add to what @Jeff Fritz has said, an IIS application creates an AppDomain in which your assemblies are loaded. Just like the rules of a normal windows application, if a class such as
...then only a single
Something.SomeString
property is available per AppDomain. The W3SVC process manages the AppDomain, but the is no guaruntee of thread safety (as an AppDomain can be service multiple requests). If you are using read-only static properties, it's probably fine (such as reading config values). If you are making mutable properties that change through the lifetime of a request, its better to use one of the storage mechanisms detailed in other questions here.