多用户ASP.NET Web应用程序中静态variables的范围

静态variables是否在用户会话中保留其值?

我有一个ASP.NET Web应用程序,我有两个button。 一个用于设置静态variables值,另一个用于显示静态variables值。

namespace WebApplication1 { public partial class WebForm1 : System.Web.UI.Page { public static int customerID; protected void Page_Load(object sender, EventArgs e) { } protected void ButtonSetCustomerID_Click(object sender, EventArgs e) { customerID = Convert.ToInt32(TextBox1.Text); } protected void ButtonGetCustomerID_Click(object sender, EventArgs e) { Label1.Text = Convert.ToString(customerID); } } } 

虽然这在单用户环境中工作,但如果两个用户同时从两台计算机login,则会发生什么情况?用户1将值设置为100,然后用户2将值设置为200.在用户1调用“获取值”button之后。 他会看到什么价值?

静态variables是否在用户会话中保留其值?

是的,这就是为什么在Web应用程序中使用静态variables时应该非常小心。 您将在并发问题中运行,因为请求的多个线程可以修改variables的值。

虽然这在单用户环境中工作,但如果两个用户同时从两台计算机login,则会发生什么情况?用户1将值设置为100,然后用户2将值设置为200.在用户1调用“获取值”button之后。 他会看到什么价值?

用户将会看到200。

静态variables范围是应用程序级别。

如果你在Staticvariables中存储了一些东西,那么你做错了事情。

如果一个用户保存数据,同时另一个用户访问同一个页面,那么他也会得到相同的数据。 所以你可以把值存储在会话中

这将为你工作(请记住,你需要处理空值/ -1):

 public static int customerID { get { return session["customerID"] == null? -1 : (int)session["customerID"]; } set { session["customerID"] = value; } } 

不要使用静态属性然后它的工作原理:

 public int customerID { get { return Session["customerID"] == null? -1 : (int)Session["customerID"]; } set { Session["customerID"] = value; } }