利用单件模式实现的数据缓存

本文介绍了一个使用.NET实现的简单数据缓存管理系统。该系统通过单例模式确保全局唯一实例,并利用哈希表存储缓存数据,同时使用队列跟踪缓存项的有效期,以定期清理过期的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


public class DataCache
{

    
public static readonly Singleton Intance = new Singleton();
    
private Singleton()
    
{
        
//
        
// TODO: Add constructor logic here
        
//
    }

    
/// <summary>
    
/// 数据
    
/// </summary>

    private Hashtable hsData = new Hashtable();

    
private Queue markQueue = new Queue();
    
/// <summary>
    
/// 缓存间隔(MIN)
    
/// </summary>

    private const  int Interval = 300;
    
/// <summary>
    
/// 获取当前应用程序指定CacheKey的Cache值
    
/// </summary>
    
/// <param name="CacheKey"></param>
    
/// <returns></returns>

    public  object GetCache(string CacheKey)
    
{
        ClearTimeOut();
        
if (hsData.ContainsKey(CacheKey))
        
{
            
return hsData[CacheKey];
        }

        
else
        
{
            
return null;
        }

    }


    
/// <summary>
    
/// 检测是否包含
    
/// </summary>
    
/// <param name="CacheKey"></param>
    
/// <returns></returns>

    public bool Contain(string CacheKey)
    
{
        
return hsData.Contains(CacheKey);
    }

    
/// <summary>
    
/// 设置当前应用程序指定CacheKey的Cache值
    
/// </summary>
    
/// <param name="CacheKey"></param>
    
/// <param name="objObject"></param>

    public  void SetCache(string CacheKey, object objObject)
    
{
        ClearTimeOut();
        
if (hsData.ContainsKey(CacheKey))
        
{
            hsData.Remove(CacheKey);
        }

        hsData.Add(CacheKey, objObject);
        TimerKeeper item 
= new TimerKeeper();
        item.Key 
= CacheKey;
        item.Stime 
= DateTime.Now;
        markQueue.Enqueue(item);
    }

    
/// <summary>
    
///  清除过期的数据
    
/// </summary>

    private  void ClearTimeOut()
    
{
        
while (markQueue.Count>0)
        
{
            TimerKeeper item 
= (TimerKeeper)(markQueue.Peek());
            TimeSpan span
=DateTime.Now.Subtract(item.Stime);
            
if (span.Seconds > Interval)
            
{
                markQueue.Dequeue();
                hsData.Remove(item.Key);
            }

            
else
            
{
                
break;
            }

        }

    }


    
private struct TimerKeeper
    
{
       
public string Key;
        
public DateTime Stime;
    }

}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值