C#:如何实现智能缓存 [英] C#: How to implement a smart cache

查看:118
本文介绍了C#:如何实现智能缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些地方,实现某种类型的缓存可能会有用.例如,在基于自定义字符串进行资源查找,使用反射查找属性名称或每个属性名称仅包含一个PropertyChangedEventArgs的情况下.

I have some places where implementing some sort of cache might be useful. For example in cases of doing resource lookups based on custom strings, finding names of properties using reflection, or to have only one PropertyChangedEventArgs per property name.

最后一个简单的例子:

public static class Cache
{
    private static Dictionary<string, PropertyChangedEventArgs> cache;
    static Cache()
    {
        cache = new Dictionary<string, PropertyChangedEventArgs>();
    }
    public static PropertyChangedEventArgs GetPropertyChangedEventArgs(
        string propertyName)
    {
        if (cache.ContainsKey(propertyName))
            return cache[propertyName];

        return cache[propertyName] = new PropertyChangedEventArgs(propertyName);
    }
}

但是,这会很好吗?例如,如果我们有很多不同的propertyNames负载,那意味着我们最终将拥有一个巨大的缓存,那里永远不会收集垃圾或任何东西.我在想,如果缓存的是更大的值,并且如果应用程序是一个长期运行的值,那么这可能最终会成为一个问题……或者您怎么看?如何实现良好的缓存?这足以满足大多数目的吗?是否有一些不错的缓存实现示例,这些实现难于理解或太复杂而难以实现?

But, will this work well? For example if we had a whole load of different propertyNames, that would mean we would end up with a huge cache sitting there never being garbage collected or anything. I'm imagining if what is cached are larger values and if the application is a long-running one, this might end up as kind of a problem... or what do you think? How should a good cache be implemented? Is this one good enough for most purposes? Any examples of some nice cache implementations that are not too hard to understand or way too complex to implement?

推荐答案

您可以将每个缓存的项目包装在

You could wrap each of your cached items in a WeakReference. This would allow the GC to reclaim items if-and-when required, however it doesn't give you any granular control of when items will disappear from the cache, or allow you to implement explicit expiration policies etc.

(哈!我只是注意到 MSDN页面上给出的示例是一个简单的缓存类.)

(Ha! I just noticed that the example given on the MSDN page is a simple caching class.)

这篇关于C#:如何实现智能缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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