Dav*_*d G 4 .net c# caching memorycache
使用时IMemoryCache
用object
,TryGetValue
永远怀念。我正在尝试将 atuple<string, object>
作为关键,并且 atuple<string, string>
工作得很好。
这里的代码总是让我缓存未命中:
_cache.TryGetValue(("typeOfCache", query), out var something);
if(something == null) _cache.CreateEntry(("typeOfCache", query));
Run Code Online (Sandbox Code Playgroud)
我使用的对象里面有列表列表,而不是没有字典/集合(没有随机排序的东西)。
这是 .net 错误还是我做错了什么?
MemoryCache
内部使用 a ConcurrentDictionary<object, CacheEntry>
,它反过来使用object
类型的默认比较器,它根据实际类型对Object.Equals
and的覆盖执行相等比较Object.GetHashCode
。在您的情况下,您的密钥是ValueTuple<string, Query>
,无论您的Query
课程是什么。ValueTuple<T1,T2>.Equals
如果比较实例的组件与当前实例的组件具有相同的类型,并且组件与当前实例的组件相同,则计算结果为真,相等性由每个组件的默认相等比较器确定。
因此,如何执行相等比较取决于您的Query
类型的实现。如果此类型不覆盖Equals
and GetHashCode
,也不实现IEquatable<T>
,则执行引用相等,这意味着您只有在传入查询的同一实例时才能获得相等。如果你想改变这种行为,你应该扩展你的Query
类来实现IEquatable<Query>
.
我还发现CreateEntry
不会立即将新条目添加到缓存中。.NET Core 文档少得令人失望,所以我还没有找到预期的行为;但是,您可以通过调用Set
来确保添加条目。
例子:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Caching.Memory;
class Program
{
static void Main(string[] args)
{
var query1 = new Query { Parts = { new List<string> { "abc", "def", "ghi" } } };
var query2 = new Query { Parts = { new List<string> { "abc", "def", "ghi" } } };
var memoryCache = new MemoryCache(new MemoryCacheOptions());
memoryCache.Set(("typeOfCache", query1), new object());
var found = memoryCache.TryGetValue(("typeOfCache", query2), out var something);
Console.WriteLine(found);
}
public class Query : IEquatable<Query>
{
public List<List<string>> Parts { get; } = new List<List<string>>();
public bool Equals(Query other)
{
if (ReferenceEquals(this, other)) return true;
if (ReferenceEquals(other, null)) return false;
return this.Parts.Length == other.Parts.Length
&& this.Parts.Zip(other.Parts, (x, y) => x.SequenceEqual(y)).All(b => b);
}
public override bool Equals(object obj)
{
return Equals(obj as Query);
}
public override int GetHashCode()
{
return this.Parts.SelectMany(p => p).Take(10).Aggregate(17, (acc, p) => acc * 23 + p?.GetHashCode() ?? 0);
}
}
}
Run Code Online (Sandbox Code Playgroud)