設想網站后台每秒自動更新一下Cache["test"]中的值,通過這個實現就可以完成一些在間隔多少時間更新一下數據庫的操作。
1、定義一個事件類BMAEvent,在Processor方法中添加間隔1秒更新一次Cache:
public class BMAEvent { private static Timer _timer;//定時器 static BMAEvent() { _timer = new Timer(new TimerCallback(Processor), null, 1000, 1000); } /// <summary> /// 此方法為空,只是起到激活BrnMall事件處理機制的作用 /// </summary> public static void Start() { } /// <summary> /// 事件處理程序 /// </summary> /// <param name="state">參數對象</param> public static void Processor(object state) { HttpRuntime.Cache.Insert("test", DateTime.Now.ToString()); } }
2、在Global.asax下Application_Start()中啟動事件
BMAEvent.Start();
3、顯示部分,在控制器中添加
public ActionResult BtnClick() { string str = "初始化..."; if (HttpRuntime.Cache["test"] != null) str= HttpRuntime.Cache["test"].ToString(); return Content(str); }
4、在頁面中添加顯示代碼,使用了ajax
<div id="result"></div> @Ajax.ActionLink("獲取值", "BtnClick", new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "result" })