using System;
using System.Threading;
using System.Collections;
namespace MyCache
{
/// <summary>
/// 实现缓存
/// </summary>
public sealed class MyCache
{
private static Hashtable Hash = Hashtable.Synchronized(new Hashtable());
private static Thread thread;
static MyCache()
{
thread = new Thread(new ThreadStart(AutoRemoveData));
thread.Start();
}
~MyCache()
{
Hash.Clear();
Hash = null;
thread.Abort();
thread = null;
}
private static void AutoRemoveData()
{
while (true)
{
foreach(object Obj in new ArrayList(Hash.Keys))
{
//清除超时没有访问量的 讨论版所占内存
if (((Data)Hash[Obj]).time< System.DateTime.Now)
{
try
{
Remove(Obj.ToString());
}
catch{}
}
}
Thread.Sleep(1000);
}
}
public static object Get(string Key)
{
if (Hash[Key] == null)
return null;
else
return ((Data)Hash[Key]).Base;
}
//超过几分钟不访问:在每次访问的时候,更改到期时间(未加代码)
public static void Set(object BaseData, string Key, int CacheTime)
{
Set(BaseData, Key, DateTime.Now.AddMinutes(CacheTime), null);
}
public static void Set(object BaseData, string Key, int CacheTime, string CallBack)
{
Set(BaseData, Key, DateTime.Now.AddMinutes(CacheTime), CallBack);
}
public static void Set(object BaseData, string Key, DateTime RemoveTime)
{
Set(BaseData, Key, RemoveTime, null);
}
public static void Set(object BaseData, string Key, DateTime RemoveTime, string CallBack)
{
if (Hash[Key] != null)
Remove(Key);
Data d = new Data(BaseData,RemoveTime,CallBack);
Hash.Add(Key,d);
}
private static void Remove(string Key)
{
if (Hash[Key] == null)
return;
Data d = (Data)Hash[Key];
if (d.CallBack != null & d.CallBack !="" & d.Base.GetType().GetMethod(d.CallBack) != null)
{
try
{
d.Base.GetType().InvokeMember(d.CallBack,System.Reflection.BindingFlags.InvokeMethod, null,d.Base,null);
}
catch
{}
}
Hash.Remove(Key);
}
private sealed class Data
{
public DateTime time;
public object Base;
public string CallBack="";
public bool IsLast = false;
public Data(object data, DateTime RemoveTime, string CallBack)
{
this.Base = data;
this.time = RemoveTime;
this.CallBack = CallBack;
}
}
}
}