访问MemoryCache是​​否会创建副本? [英] Does accessing MemoryCache create a copy?

查看:54
本文介绍了访问MemoryCache是​​否会创建副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的缓存服务:

public interface ICacheService {
    T Get<T>(string cacheID, Func<T> getItemCallback, int cacheMinutes = 5) where T : class;
}

public class MemoryCacheService : ICacheService {
    public T Get<T>(string cacheId, Func<T> getItemCallback, int cacheMinutes = 5) where T : class {
        T item = MemoryCache.Default.Get(cacheId) as T;
        if (item == null) {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheId, item,
                new CacheItemPolicy {AbsoluteExpiration = DateTime.Now.AddMinutes(cacheMinutes)});
        }
        return item;
    }
}

并按以下方式检索:

var result = _cache.Get("mylist", () => _database.Fetch<MyList>().AsQueryable(), 600);

该列表很大,并且在每个击键提前键入下拉列表中经常访问.而且查询条件也是动态的,例如

The list is large and accessed frequently in a per keystroke type-ahead dropdown. And the query condition is also dynamic, like

if (this) result = result.Where(x=> this ...)
if (that) result = result.Where(x=> that ...)
finally result.ToList() 

我想知道,每次我从缓存访问列表时,系统是否在开始构建linq查询之前创建数据的副本?如果是这样,那就像按击键复制一样,效率不高.还是因为我正在检索AsQueryable并构建linq而推迟了查询?

I wonder, every time I access the list from cache, does the system create a copy of the data before start building linq query? If so, it's like copy-per-keystroke, not very efficient. Or does the it deferred the query because I'm retrieving AsQueryable and build linq?

还有更好的选择吗?谢谢

Any better alternatives? Thanks

推荐答案

否,MemoryCache不会复制.基本上,您将对某个对象实例的引用存储在缓存中,这就是您访问缓存中的项时所获得的.

No, MemoryCache does not make a copy. You basically store a reference to some object instance in the cache, and that is what you get back when you access an item in the cache.

我没有正式的文档链接,但是在实践中发现了困难的方式",在那儿,我不小心使用了我返回的引用(不复制它)来修改了缓存的对象.

I don't have a formal documentation link, but found out the "hard way" in practice, where I accidentally modified the cached object by just using the reference I got back (without copying it).

另外,研究参考源( http://referencesource.microsoft.com )显示没有参考源.自动复制.

Also, studying the reference sources (http://referencesource.microsoft.com) shows that there is no automatic copying happening.

根据您的应用程序和需求,您可能想要确保缓存的类型实际上是设计不变的.

Depending on your application and needs, you might to want sure that the types you cache are actually immutable by design.

这篇关于访问MemoryCache是​​否会创建副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆