从MemoryCache

时间:2016-08-01 19:57:16

标签: c# .net memorycache

我实现了一个带有派生CacheItem的MemoryCache,但是一旦它在缓存中就很难与之交互。例如:

class Program
{
    static void Main(string[] args)
    {
        MemoryCache cache = MemoryCache.Default;
        CacheItemPolicy policy = new CacheItemPolicy();
        CustomCacheItem someItem = (CustomCacheItem)cache.AddOrGetExisting(new CustomCacheItem(1, "tacos", "waffles"), policy);

        Console.ReadLine();
    }
}

public class CustomCacheItem : CacheItem
{
    public int FailureCt { get; set; }

    public CustomCacheItem(int _failureCt, string _key, string _value)
        : base(_key, _value)
    {
        FailureCt = _failureCt;
    }
}

这会引发Unable to cast object of type 'System.Runtime.Caching.CacheItem' to type 'CacheTest.CustomCacheItem'.错误,这是有道理的;也许它不会保留有关放入缓存项的信息。但如果是这样,我如何获取自定义缓存项?如果返回值是通用基类型,我如何与该属性进行交互(在本例中为FailureCt)?

1 个答案:

答案 0 :(得分:1)

原因是MemoryCache.AddOrGetExisting(CacheItem, CacheItemPolicy)在内部创建了新的CacheItem

public override CacheItem AddOrGetExisting(CacheItem item, CacheItemPolicy policy)
{
    if (item == null)
        throw new ArgumentNullException("item");
    return new CacheItem(item.Key, AddOrGetExistingInternal(item.Key, item.Value, policy));
}

MemoryCache source code

我建议将FailureCt存储在值本身而不是CacheItem包装器中:

public class CacheValue
{
    public int FailureCt { get; set; }
    public string Value { get; set; }
}

然后:

CacheValue someItem = (CacheValue)cache.AddOrGetExisting("tacos", new CacheValue()
{
    FailureCt = 1,
    Value = "waffles"
}, policy);