Monday, April 6, 2009

ASP.NET Static variable

Let's examine behavior of static keyword in ASP.NET

Create a class TestStatic with static member.

public class TestStatic
{
private static string strTest = string.Empty;

public static string Test
{
get
{
return strTest;
}
set
{
strTest = value;
}
}
}


Create a aspx page and place two buttons on it. On click of Button1 event assign value to Test along with with DateTime.

protected void Button1_Click(object sender, EventArgs e)
{
TestStatic.Test = "Logged in successfully" + DateTime.Now.ToLongTimeString();
}

and on click of button2 event write the value of Test on the page

protected void Button2_Click(object sender, EventArgs e)
{
Response.Write(TestStatic.Test);
}

Run the application and click Button1, now value has been assigned into TestStatic. Test will contain "Logged in successfully" along with date time stamp.

Now click on Button2, the value assigned into TestStatic.Test will be displayed on the page with time stamp.






Now open another browser instance(using start menu or shortcut in taskbar or shortcut in desktop). Copy URL of above test application and paste on the address bar of the browser and hit enter. Obviously you will get both the buttons (Button1 & Button2).
I have used FireFox.

Don't click on Button1, Click on Button2. You will get the value of TestStatic.Test.
The value of TestStatic.Test displayed on the page will be the value which has been assigned using last browser.



This behavior is obvious because ASP.NET is multi threaded application, so the value of static member shared between threads.

Bottomline is, be carefull while using static variable in ASP.NET as it might put your application in weired situation. Use static variable only when you are sure static variable will be accessed in thread safe manner.

Happy Coding :)

2 comments:

Jignesh Patel said...

thanks for nice article keep it up....

Anonymous said...

thank you very very very much!!! :)

Site Meter