aspx是否为c#静态变量提供特殊处理

在.net web应用程序中,有一些关于.aspx页面的特殊内容以及改变静态变量行为的页面后面的c#代码。

我有大量的应用程序页面是在别处开发的,并且有一个共同的模式运行通过它们我认为应该是一个实例变量被声明为一个静态变量。

更详细的问题陈述是:如果我有两个Web会话a和b在同一个应用程序池中的同一个iis服务器上运行,如果访问有问题的页面并将静态变量x设置为value1然后b访问相同的页面并将静态变量x设置为值2,我的理解是value1已被值2替换。我的困境是这个模式在代码中重复使用,在高级别代码似乎工作。 结论是它要么运气好(会话中的时间a在会话b击中它之前已经放弃了变量的需要),要么还有其他事情发生。

我愿意接受有关ac#nuance或开发人员错误的建议。

静态属性/字段在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 } } 

在流量显着之前,您可能看不到问题。 假设页面检索值,将其放入静态变量,使用一次,然后完成执行。 如果页面快速执行,除非时间正确和/或流量足够高,否则您可能看不到非常小(但危险!)的重叠窗口。

这可能导致难以诊断的错误,因为它们依赖于时间,并且您可能在自己在本地计算机上进行测试时看不到它们。