在 .net 网络应用程序中,.aspx 页面和改变静态变量行为的页面背后的 C# 代码有一些特殊之处。
我有大量在其他地方开发的应用程序页面,并且有一个共同的模式贯穿其中,我认为应该是实例变量的地方被声明为静态变量。
问题的更详细说明是:如果我有两个 Web session a 和 b 在同一个应用程序池中的同一个 iis 服务器上运行,如果 a 访问有问题的页面并将静态变量 x 设置为 value1,然后b 访问同一页面并将静态变量 x 设置为值 2,我的理解是值 1 已被值 2 替换。我的困境是代码中重复使用了这种模式,在较高级别代码似乎可以工作。结论是这要么是运气(在 session a 中的时间在 session b 命中它之前放弃了对变量的需求),要么是有其他事情发生。
无论这是 C# 细微差别还是开发人员错误,我都乐于接受建议。
最佳答案
静态属性/字段在 Web 应用程序中很好,只要它们用于可以随时消失的共享数据,例如当应用程序池回收时。
也就是说,它们的值确实在 ASP.Net 应用程序内部共享,除非它们具有隔离的支持机制,例如 Session
。
例子
public static int UserId = 10; // BAD! everyone gets/sets this field's value
// BAD! everyone gets/sets this property's implicit backing value
public static int UserId {
get;
set;
}
// This case is fine; just a shortcut to avoid instantiating an object.
// The backing value is segregated by other means, in this case, Session.
public static int UserId{
get{
return (int)HttpContext.Current.Session["UserId"];
}
}
// While I would question doing work inside a property getter, the fact that
// it is static won't cause an issue; every call retrieves data from a
// database, not from a single memory location.
public static int UserId{
get{
// return some value from database
}
}
除非流量很大,否则您可能看不到问题。假设一个页面检索一个值,将它放在一个静态变量中,使用一次,然后完成执行。如果页面执行速度很快,除非时机正确和/或流量足够高,否则您可能看不到非常小(但很危险!)的重叠窗口。
这可能会导致难以诊断的错误,因为它们取决于时间,您在本地计算机上自行测试时可能看不到它们。
关于c# - aspx 是否为 c# 静态变量提供特殊处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11738455/