温馨提示×

如何利用c# dictionary实现缓存机制

c#
小樊
84
2024-08-27 15:07:36
栏目: 编程语言

在C#中,可以使用Dictionary类来实现一个简单的缓存机制

  1. 首先,创建一个缓存类,它将包含一个Dictionary对象,用于存储键值对。还需要定义一个过期时间,用于设置缓存项的生命周期。
using System;
using System.Collections.Generic;

public class Cache<TKey, TValue>
{
    private readonly Dictionary<TKey, Tuple<DateTime, TValue>> _cache = new Dictionary<TKey, Tuple<DateTime, TValue>>();
    private readonly TimeSpan _expirationTime;

    public Cache(TimeSpan expirationTime)
    {
        _expirationTime = expirationTime;
    }
}
  1. 向缓存类添加一个方法,用于向缓存中添加项。这个方法应该接收一个键、一个值和一个可选的过期时间。如果没有提供过期时间,则使用默认的过期时间。
public void Add(TKey key, TValue value, TimeSpan? expirationTime = null)
{
    var expiration = DateTime.UtcNow.Add(expirationTime ?? _expirationTime);
    _cache[key] = Tuple.Create(expiration, value);
}
  1. 向缓存类添加一个方法,用于从缓存中获取项。这个方法应该接收一个键,并返回相应的值(如果找到)。如果项已过期或不存在,则返回null。
public TValue Get(TKey key)
{
    if (_cache.TryGetValue(key, out var item))
    {
        if (item.Item1 > DateTime.UtcNow)
        {
            return item.Item2;
        }
        else
        {
            // Remove expired item
            _cache.Remove(key);
        }
    }
    return default(TValue);
}
  1. (可选)向缓存类添加一个方法,用于清除缓存中的所有项。
public void Clear()
{
    _cache.Clear();
}

现在你可以使用这个缓存类来存储和检索数据。例如:

var cache = new Cache<string, string>(TimeSpan.FromMinutes(5));

// Add items to the cache
cache.Add("key1", "value1");
cache.Add("key2", "value2", TimeSpan.FromMinutes(1));

// Retrieve items from the cache
var value1 = cache.Get("key1");
var value2 = cache.Get("key2");

// Clear the cache
cache.Clear();

这个缓存类非常简单,主要用于演示目的。在实际项目中,你可能需要考虑更多的功能,例如线程安全、持久化和错误处理等。

0