【问题标题】:Getting custom CacheItems from MemoryCache从 MemoryCache 获取自定义 CacheItems
【发布时间】:2016-08-01 19:57:16
【问题描述】:

我正在使用派生的 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)进行交互?

【问题讨论】:

  • 从CacheItem派生的目的是什么? CacheItem 只是作为缓存的入口和数据的包装器。 CacheItem item = (CacheItem)cache.AddOrGetExisting(new CacheItem(1, "tacos", "waffles"), policy); item.value 会给你数据。 请注意,按照文档状态,如果密钥存在,这将返回 null https://msdn.microsoft.com/en-us/library/dd988741.aspx
  • @hdz 是的,我认为我对如何在更大的缓存结构中使用 CacheItem 有一个错误的假设。我以为所有额外的信息都与它一起存储,但似乎并非如此。

标签: c# .net memorycache


【解决方案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);

【讨论】:

  • 啊,有趣。我想我有一个错误的假设,即 CacheItem 是我应该覆盖的,而不仅仅是值。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
  • 2012-12-20
  • 2014-01-06
  • 2012-04-30
  • 2018-03-06
  • 1970-01-01
相关资源
最近更新 更多