static变量生命周期小研究

A页面:定义一个普通类,类包含一个静态变量a,值为:111111111111111111

B页面:修改a的值为:22222222222222

C页面:用来查看a的值

 

1.在vs2008中,先打开B,再打开C,C显示a的值为:222222222222222

就算用ie打开B,用chrome打开C,C仍然显示为:22222222222222,证明与客户端无关;

2.在IIS中,直接打开C,显示为:11111111111111111

证明静态变量的值与服务器有关

3.在IIS中,先打开B,再打开C,C显示a的值为:222222222222222

重启IIS,再打开C,C显示为:11111111111111111,证明服务器生命到期,静态变量也跟着死掉掉~

4.在IIS中,打开B,在虚拟机中,打开宿主机IIS的C,显示为:222222222222222

再次证明与客户端无关,即在实际使用中,不同客户端用户使用的是同一个变量值。

 

花了2个小时实验出来的,记录一下,要不然过不了一两个月,就只有上帝记得这次的实验结果了。

=================================================

PS:顺便也测试了一下多线程thread

同时用IE和chrome打开,日志记录为:

2014-10-30 14:27:11: 子线程:2014-10-30 14:27:11
====================================================
2014-10-30 14:27:12: 子线程:2014-10-30 14:27:12
====================================================

证明不同请求,线程间无任何关联,更谈不上互斥。

 1 public partial class test_testThread : System.Web.UI.Page
 2 {
 3     private Object thisLock = new Object();
 4     public string str = string.Empty;
 5 
 6     protected void Page_Load(object sender, EventArgs e)
 7     {
 8         Thread xThread1 = new Thread(new ThreadStart(this.threadFun));
 9         xThread1.Start();
10     }
11 
12     private void threadFun()
13     {
14         lock (thisLock)
15         {
16             string nowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
17             WriteLog("子线程:" + nowTime);
18             Thread.Sleep(10000);
19         }
20     }
21 
22     private void WriteLog(string sLog)
23     {
24         sLog += "\n====================================================";
25         string sFileName = "testThread_" + DateTime.Now.ToString("yyyy-MM-dd_") + ".txt";
26         string sFileFullPath = AppDomain.CurrentDomain.BaseDirectory + "test\\" + sFileName;
27         System.IO.StreamWriter sw = System.IO.File.AppendText(sFileFullPath);
28         sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss: ") + sLog);
29         sw.Close();
30     }
View Code

 

posted @ 2014-10-29 19:58  陈少鑫  阅读(1239)  评论(0编辑  收藏  举报