开发者

static variable in asp.net web application

开发者 https://www.devze.com 2023-03-10 09:12 出处:网络
I have: MyNameSpace.MyClass1 MyNameSpace.MyClass2 i need to get value from MyClass1.myvar1 from MyClass2.

I have:

  1. MyNameSpace.MyClass1
  2. MyNameSpace.MyClass2

i need to get value from MyClass1.myvar1 from MyClass2. Should I do that with static varia开发者_StackOverflow社区ble

What happens with variable value if it is static in a web application. Im using MyClass1 as: var mClass=new MyNameSpace.MyClass1(), and from that im using mClass.

thank you


No, you should not use a static variable here. Remember, static means the variable is global for the application. In ASP.Net, you have a single application instance that is shared among everyone who visits your site. Using static variables can result in one user seeing another user's data.


If the value context is global, than it is ok to use static variable. Remember that if the value is updated, its updated for all users. If the data is different or belong to a user, than never use static, instead instantiate object of MyClass1 inside MyClass2 method .

you can use following approach.

Declare MyClass1.myvar1 as public and access from MyClass2.

class MyClass1{
public int myvar1 = 7;
}

class MyClass2{
 public void TestMethod(){
  MyClass1 obj = new MyClass1();
  int val = obj.myvar1; 
 }
}

In this case, your data is safe.


It is not OK to use a static variable within ASP.NET unless you take thread safety into account. A single request will generally run on a single thread. Different requests will probably run on different threads. (See http://blogs.msdn.com/b/tmarq/archive/2010/04/14/performing-asynchronous-work-or-tasks-in-asp-net-applications.aspx for some good threading information.)

Unless you study up on writing thread safe code, I would consider using the following objects instead to maintain static data:

  1. Application - for application-wide static data
  2. Session - if it's user specific static data
  3. HttpContext.Items - if it's data to be used by different objects within a single request
  4. HttpRuntime.Cache / HttpContext.Cache - to cache shared data that can have expirations / dependencies


All youneed is to make a new instance of your class2 and call your variable from created instance in class1 like

myclass1
{
    string Variable = string.empty;
    protected void YourMethod()
    {
        myclass2 c2 = new myclass2()
        this.Variable = c2.Variable;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号