在多用户ASP.NET Web应用程序中的静态变量范围 [英] Scope of static Variable in multi-user ASP.NET web application

查看:106
本文介绍了在多用户ASP.NET Web应用程序中的静态变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问静态变量跨用户会话保留其值?

我有一个ASP.NET Web应用程序在那里我有两个按钮。一个用于设置静态变量的值,另一个用于显示静态变量的值。

 命名空间WebApplication1
{公共部分类WebForm1的:System.Web.UI.Page
{
    公共静态INT的customerID;    保护无效的Page_Load(对象发件人,EventArgs的发送)
    {    }    保护无效ButtonSetCustomerID_Click(对象发件人,EventArgs的发送)
    {
        的customerID = Convert.ToInt32(TextBox1.Text);
    }    保护无效ButtonGetCustomerID_Click(对象发件人,EventArgs的发送)
    {
        Label1.Text = Convert.ToString(的customerID);
    }
}}

虽然,发生什么,如果有2个用户在两台计算机,用户1套价值为100,那么用户2台价值200同时登录后用户1调用得到这个工作在单用户环境值按钮。什么将他作为值看?


解决方案

  

请问静态变量跨用户会话保留其值?


是的,这就是为什么当你在一个Web应用程序使用静态变量,你应该非常小心。您将在并发问题作为运行多个线程提供服务的请求可以修改变量的值。


  

虽然这个工作在单用户环境中,如果有,会发生什么
  2个用户同时从两台电脑,用户1套记录在
  值100,那么用户2用户1后,设定值为200。
  调用get值按钮。什么将他作为值看?


该用户将看到200之后。

Does static variables retain their values across user sessions?

I have a ASP.NET web application where I have two buttons. One for setting the static variable value, another for Showing the static variable value.

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);
    }
}

}

While this works in single-user environment, What happens if there are 2 users simultaneously logged in from two computers, User 1 sets the value as 100, then User 2 sets the value as 200. after that user 1 invokes the Get Value button. What will he see as the value?

解决方案

Does static variables retain their values across user sessions?

Yes, that's why you should be VERY careful when you use static variables in a web app. You will run in concurrency issues as more than one thread servicing a request can modify the value of the variable.

While this works in single-user environment, What happens if there are 2 users simultaneously logged in from two computers, User 1 sets the value as 100, then User 2 sets the value as 200. after that user 1 invokes the Get Value button. What will he see as the value?

The user will see 200 afterwards.

这篇关于在多用户ASP.NET Web应用程序中的静态变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆