首先请看如下的代码:
以上演示了
Session,
ViewState,
Cache的基本操作,以及
Application的用法。
其中, Application因为涉及到并发问题,在操作 Application的事后一般会采取锁机制。这样就可以使用 Application来实现计数器等的功能了。
当然,我们也可以使用 lock 模块来实现这种锁机制。
关于缓存的说明,请参照:
http://www.cnblogs.com/shimeng3344518/archive/2007/05/15/747606.html
http://stor.chinaunix.net/stor/m/2008/07/15/1200353.shtml
http://www.qqread.com/aspdotnet/p392191.html
http://www.dreamsun.cn/web/show.asp?id=1513
http://www.opent.cn/?action=show&id=203
http://www.nuli365.com/ReadCode.aspx?id=401
- using System;
- using System.Data;
- using System.Configuration;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.Caching;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Web.UI.HtmlControls;
- public partial class _Default : System.Web.UI.Page
- {
- private static int counter = 0;
- private static object lockObject = new object();
- private static object catheSynchronize = new object();
- protected void Page_Load(object sender, EventArgs e)
- {
- ViewState["NUM"] = 4;
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- //1
- Application.Lock();
- if (Application["HitCounter"] == null)
- {
- Application["HitCounter"] = 0;
- }
- Application["HitCounter"] = (int)Application["HitCounter"] + 1;
- Application.UnLock();
- //2
- lock (lockObject)
- {
- counter++;
- }
- //3
- Session["NUM"] = 10000;
- if (Cache["NUM_CACHE"] == null)
- {
- lock (catheSynchronize)
- {
- if (Cache["NUM_CACHE"] == null) {
- //Cache["NUM_CACHE"] = 100;
- CacheDependency cd = new CacheDependency(Server.MapPath("aaaa.xml"));
- Cache.Insert("NUM_CACHE", "OOOOOK", cd, DateTime.Now.AddMinutes(2), Cache.NoSlidingExpiration);
- }
- }
- }
- //Cache.Remove("NUM_CACHE");
- Response.Redirect(string.Format("TestPage.aspx?type={0}", counter));
- }
- }
- using System;
- using System.Data;
- using System.Configuration;
- using System.Collections;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Web.UI.HtmlControls;
- public partial class TestPage : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- //Label1.Text = Convert.ToString(Session["NUM"]);
- //Label1.Text = Convert.ToString(ViewState["NUM"]);
- Label1.Text = Convert.ToString(Cache["NUM_CACHE"]);
- //Label1.Text = Convert.ToString(Request.QueryString["type"]);
- }
- }
其中, Application因为涉及到并发问题,在操作 Application的事后一般会采取锁机制。这样就可以使用 Application来实现计数器等的功能了。
当然,我们也可以使用 lock 模块来实现这种锁机制。
关于缓存的说明,请参照:
http://www.cnblogs.com/shimeng3344518/archive/2007/05/15/747606.html
http://stor.chinaunix.net/stor/m/2008/07/15/1200353.shtml
http://www.qqread.com/aspdotnet/p392191.html
http://www.dreamsun.cn/web/show.asp?id=1513
http://www.opent.cn/?action=show&id=203
http://www.nuli365.com/ReadCode.aspx?id=401