同一 ASPX 页面的所有实例是否共享相同的静态字段?
让我们考虑一下这个页面的代码隐藏:
public partial class Products : Page
{
private static SomeClass SharedField;
public Product()
{
// ... Some logic
}
}
所有Products
页面实例是否共享相同的SharedField
,我知道这是静态字段的基本概念。但在这种情况下,真的吗?所有用户都可以访问(并且不能拥有自己的实例)网站级别的同一静态字段?
如果是这样,网络开发人员会在哪些方面使用它?或者这是不推荐的做法?
Let's consider this page's code-behind:
public partial class Products : Page
{
private static SomeClass SharedField;
public Product()
{
// ... Some logic
}
}
Do all Products
pages instances share the same SharedField
, I know this is a basic concept of static fields. But in this case, really? all users can have access (and can't have their own instance of) to the same static field on the website-level?
If so, in what aspects this would used by the web developer? or is this non-recommended practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,所有用户都会有该静态字段的单个实例,但仅限于单个工作进程内。如果您有网络农场/网络花园,它们每个都有自己的静态实例。如果工作进程重新启动,您将获得一个新的静态实例。
您必须在该共享字段周围使用锁定来确保线程安全。
至于为什么要用它,我不确定,我从来没有这样做过。我可以给你的最好的例子是内置的静态
HttpContext.Current
,它使你可以访问请求、响应等。Yes, there will be a single instance of that static field for all users, but only within a single worker process. If you have web farms/web gardens, they will each have their own static instance. If the worker process restarts, you'll get a new static instance.
You'll have to use locking around that shared field to ensure thread safety.
As for why to use that, I'm not sure, I never do it. The best example I can give you is the built-in static
HttpContext.Current
, which gives you access to the Request, Response, etc.SharedField
将在网站的整个生命周期的一个实例中可用。要了解更多相关信息,查看此答案。
SharedField
will be available in one instance for the entire life-cycle of the web site.To read a bit more about it, see this answer.
更好的做法是将对象存储在应用程序状态中。
Application["MyObject"] = new SomeClass();
A better practice would be to store your object in the Application state.
Application["MyObject"] = new SomeClass();