开发者

Updating coordinated dictionaries in C#

I have two dictionaries that are acting as a cache, let's call them d1 and d2, with d2 being a subset a of d1.

When I refresh the dictionaries with new entries of d1, I would like the entries in d2 to be refreshed as well. It can be done the obvious way:

foreach(var update in updates) {
    d1[update.id] = update;
    if(d2.Contains(update.id))
        d2[update.id] = update;
}

But sinc开发者_StackOverflow中文版e I'd like to cache other subsets (d3,d4,d5, etc), this may get unwieldy. So I added a "CopyFrom" method to my object, which allows me to maintain the reference by simply just copying properties to the object being updated.

foreach(var update in updates) {
    d1[update.id].CopyFrom(update)
}

In this way, any other dictionaries that have a reference to the entry won't lose it when d1 gets updated.

I'd just like to know if I'm missing anything here? I'm just getting back into C# after a break, and my grasp on the obvious may be shaky :).


Why not have a CacheItem class that contains the payload (the current values in your dictionaries). Then for each key in your dictionaries, store a CacheItem containing what you're currently storing. If you store the same CacheItem object in multiple dictionaries, you only need to modify the payload of a CacheItem, and all the dictionaries containing it are updated.

foreach(var update in updates) {
    if (d1.ContainsKey(update.id)) {
        var cacheItem = d1[update.id];
        cacheItem.Payload = update;
    } else {
        d1[update.id] = new CacheItem(update);
    }
}

My answer assumes that your design of having multiple dictionaries, some being subsets of the main one is based on your requirements, and is a sound way to address them. It seems a little unusual to me.


Well if the value of the Dictionary is a reference type, and you're only modifying it, you wouldn't need to do anything. If you are creating a new reference or it is a value type, I'd change the subsets to be arrays of the type of id which is the subset you'd like to have. And whenever you need the value, you'd still go to d1 for accessing it.


As for all types of cache keep in mind that a cache with a bad policy is another name for a memory leak.

Further: Caching Implies Policy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜