溫馨提示×

如何利用c# dictionary實現緩存機制

c#
小樊
150
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女