ConcurrentDictionary TryUpdate相等比较器

时间:2015-07-29 07:14:51

标签: c# concurrentdictionary

我有一个ConcurrentDictionary,我用它作为哈希表,将以固定的时间间隔刷新。我的ConcurrentDictionary的TValue是我创建的自定义类:

public class RefreshableDictionaryValue<TValue>
{
    private DateTime lastRefreshed;
    private DateTime lastAccessed;
    private TValue value;

    public override bool Equals(object obj)
    {
        if (obj == null)
        {
            return false;
        }

        TValue t = (TValue)obj;
        if((System.Object)t == null)
        {
            return false;
        }

        return this.Value.Equals(((RefreshableDictionaryValue<TValue>)obj).Value);
    }
    public override int GetHashCode()
    {
        return Value.GetHashCode();
    }
    ...
}

我假设ConcurrentDictionary使用equals比较两个对象的值,并且我已经覆盖了我的类的Equals,因此如果TValues相等则返回true。日期可能不同。我也试过IEqualityComparer<RefreshableDictionaryValue<TValue>>但是没有效果。

如果我不重写Equals,则TryUpdate返回false(显然,导致我正在比较的对象将具有相同的TValue但不同的日期)并且如果我覆盖equals我得到此错误

> Error while refreshing dictionary System.InvalidCastException: Unable
> to cast object of type
> ItemRefreshableDictionary.RefreshableDictionaryValue`1[StatsHelper.Stats]'
> to type 'StatsHelper.Stats'.    at
> ItemRefreshableDictionary.RefreshableDictionaryValue`1.Equals(Object
> obj) in
> \Projects\StatsHelper\ItemLevelRefreshableDictionary\ItemLevelRefreshableDictionary.cs:line
> 24    at System.Collections.Generic.ObjectEqualityComparer`1.Equals(T
> x, T y)    at
> System.Collections.Concurrent.ConcurrentDictionary`2.TryUpdate(TKey
> key, T Value newValue, TValue comparisonValue)

修改 以下是我更新的方式:

foreach(KeyValuePair<TKey, RefreshableDictionaryValue<TValue>> entry in cacheDictionary)
{
    DateTime lastRefresh = entry.Value.LastRefreshed;
    DateTime lastAccess = entry.Value.LastAccessed;

    secondsSinceLastRefresh = Convert.ToInt32((DateTime.Now - lastRefresh).TotalSeconds);
    secondsSinceLastAccess = Convert.ToInt32((DateTime.Now - lastAccess).TotalSeconds);
    if (secondsSinceLastAccess < cacheExpirationTime)
    {
        if (secondsSinceLastRefresh > refreshInterval)
        {
            TValue updatedValue = valueGetter(entry.Key);

            bool s = cacheDictionary.TryUpdate(entry.Key, new RefreshableDictionaryValue<TValue>(DateTime.Now, lastAccess, updatedValue), entry.Value);
        }
     }
 }

0 个答案:

没有答案