Asp.net中Application的收尾事件的触发

根据我之前的谷歌一下,貌似很多人都表示Application的各个事件(尤其是各种收尾事件)的触发十分诡异。

而且这些事件还十分有用。比如说如果用Application作缓存,用户输入的东西先不直接存储在数据库中而先保存到Application中,直到Application到达一定大小时再一起存储进数据库。如果Application在销毁时不利用事件将剩余的数据存储,那么那些数据就将丢失。

于是刚才做了个小程序尝试了一下。在global.asax里写下这个:

protected void Application_End(object sender, EventArgs e)
{
    System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\1.txt",true);
    sw.WriteLine("End " + DateTime.Now.ToString());
    sw.Close();
}
protected void Application_Disposed(object sender, EventArgs e)
{
    System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\1.txt", true);
    sw.WriteLine("Disposed " + DateTime.Now.ToString());
    sw.Close();
}
public override void Dispose()
{
    System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\1.txt", true);
    sw.WriteLine("Dispose " + DateTime.Now.ToString());
    sw.Close();
    base.Dispose();
}

然后在default.aspx.cs文件中写下这个:

protected void Page_Load(object sender, EventArgs e)
{
    System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\1.txt", true);
    sw.WriteLine("Begin");
    sw.Close();
    Label1.Text = (Application["time"] == null ? "" : (Application["time"] as string));
}

protected void Button1_Click(object sender, EventArgs e)
{
    Application.Add("time", DateTime.Now.ToString());
}

首先用chrome运行default.aspx(为啥必须用chrome一会儿再说),发现1.txt中出现begin,证明有写权限;

然后点击Button1,刷新后发现Label1中出现时间,说明时间已存入Application中;

然后打开iis,重启网站。发现1.txt中多出了三次时间,顺序是override Dispose, Disposed, End;

然后刷新网页,发现网页上的时间已经消失,说明application已被清除;

再次打开iis,重启网站。发现1.txt中又多出了三次时间,说明application的用于结束的事件在application未改变时也会触发;

然后再次立即重启网站。发现1.txt中未增加数据,说明application的用于结束的事件仅在有过session的情况才触发;

然后刷新网页,点击按钮,之后在web.config的某一行末尾添加空格,保存后发现1.txt末尾多出三次时间,刷新网页发现网页上的时间消失,说明web.config变化和重启网站有相同的作用。

刷新网页,重启电脑,再次启动时发现1.txt末尾出现多出三次时间。说明重启电脑(停止iis再启动)依然会触发事件,前提是有过session的情况下。

现在我解释为啥不能用ie:因为ie的缓存机制很怪异,有时候打开一个打开过的网页不会连接服务器,甚至刷新也不一定会连接服务器。

希望对依然纠结在这方面的人有帮助~

发表评论