Skip to content

KeyNotFoundException in CacheEntry's finalizer #25

@GoogleCodeExporter

Description

@GoogleCodeExporter
A weird, random thing happened to me today: cache[t] threw KeyNotFoundException 
in CacheEntry's finalizer, where t was typeof(Int64).

~CacheEntry()
{
    lock (cache)
    {
        if (cache[t].Target == this || cache[t].Target == null)
            cache.Remove(t);
    }
}

I thought of a way this bug could be triggered:

(1) Someone calls GetCacheEntry(Int64), which locks the cache
(2) The finalizer for the CacheEntry of Int64 starts and cannot acquire the 
lock, so it enters a wait state
(3) GetCacheEntry can't find Int64 in the cache so it creates a new CacheEntry 
for it
(4) GetCacheEntry releases the lock and the finalizer of CacheEntry acquires it
(5) Int64 is removed from the cache, but a second CacheEntry for Int64 still 
exists
(6) The finalizer of the second CacheEntry is called at some later time, which 
causes the KeyNotFoundException.

Workaround (not sure if it's perfectly safe): ~CacheEntry should use 
cache.TryGetValue instead.

Original issue reported on code.google.com by qwertie...@gmail.com on 5 Jan 2011 at 12:52

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions