⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 应用程序缓存_例1.txt

📁 C# 是创新性的新式编程语言
💻 TXT
字号:
应用程序缓应用:

1.使用回调函数保持文件内容与缓存中的相同。
2.减少文件物理访问,提高程序性能。
3.更改文件将引起回调Quotes.txt。

3.Cache的生命期(与Application相)
1.关闭IE时仍然存在。
2.重启IIS(重启计算机、关机)时会丢失。
3.刷新时仍然存在。
5.关闭IE,应用程序并没有结束,Cache中的数据仍然存在
6.在Application_Eend无法捕捉Cache.
示例功能:随机显示保存在一个文本文件中的名人名言。


1.WebForm1.aspx
private void Page_Load(object sender, System.EventArgs e)
		{
			ArrayList quotes = (ArrayList) Cache["Quotes"];

			if (quotes != null) 
			{
				Random rand = new Random ();
				int index = rand.Next (0, quotes.Count - 1);
				Label1.Text = (string) quotes[index];
			}
			else 
			{
				Label1.Text = "Server busy";
			}
		}

2.Global.asax.cs(注意添加 using System.Web.Caching;)
using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
using System.IO;
using System.Web.Caching;
namespace MySmart 
{
	/// <summary>
	/// Global 的摘要说明。
	/// </summary>
	public class Global : System.Web.HttpApplication
	{
		/// <summary>
		/// 必需的设计器变量。
		/// </summary>
		private System.ComponentModel.IContainer components = null;
		static Cache _cache = null;
		static string _path = null;

		public Global()
		{
			InitializeComponent();
		}	
		
		protected void Application_Start(Object sender, EventArgs e)
		{
			_cache = Context.Cache;
			_path = Server.MapPath ("Quotes.txt");

			ArrayList quotes = ReadQuotes ();

			if (quotes != null) 
			{
				_cache.Insert ("Quotes", quotes, new CacheDependency (_path),
					Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
					CacheItemPriority.Default,
					new CacheItemRemovedCallback (RefreshQuotes));
			}
		}
               //回调函数
		static void RefreshQuotes (String key, Object item,
			CacheItemRemovedReason reason)
		{
			ArrayList quotes = ReadQuotes ();

			if (quotes != null) 
			{
				//永不过期
                                 _cache.Insert ("Quotes", quotes, new CacheDependency (_path),
					Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
					CacheItemPriority.Default,
					new CacheItemRemovedCallback (RefreshQuotes));
			}
		}

		static ArrayList ReadQuotes ()
		{
			ArrayList quotes = new ArrayList ();
			StreamReader reader = null;

			try 
			{
				reader = new StreamReader (_path);
				for (string line = reader.ReadLine (); line != null;
					line = reader.ReadLine ())
					quotes.Add (line);
			}
			catch (IOException) 
			{
				return null;
			}
			finally 
			{
				if (reader != null)
					reader.Close ();
			}
			return quotes;
		}


	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -