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

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

问题描述

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

Does static variables retain their values across user sessions?

我有一个 ASP.NET Web 应用程序,其中有两个按钮.一个用于设置静态变量值,另一个用于显示静态变量值.

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

}

虽然这在单用户环境中有效,但如果有 2 个用户同时从两台计算机登录会发生什么情况,用户 1 将值设置为 100,然后用户 2 将值设置为 200.之后用户 1 调用 Get值按钮.他会看到什么价值?

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?

是的,这就是为什么在 Web 应用程序中使用静态变量时应该非常小心的原因.您将遇到并发问题,因为为一个请求服务的多个线程可以修改变量的值.

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.

虽然这在单用户环境中有效,但如果有2 个用户同时从两台计算机登录,用户 1 设置值为 100,然后用户 2 将值设置为 200.在用户 1 之后调用获取值按钮.他会看到什么价值?

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?

用户会在之后看到 200.

The user will see 200 afterwards.

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

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