WeakReference和缓存

时间:2015-01-30 14:38:04

标签: c#

我有一个用于管理指定类型的通用缓存,但是,它并没有像我预期的那样工作。这是我的实施:

public class GCManagedCache<T> where T : class
{
    private readonly Dictionary<string, WeakReference> _cache = new Dictionary<string, WeakReference>();

    public T this[string key]
    {
        get
        {
            WeakReference weakRef = null;
            if (!_cache.TryGetValue(key, out weakRef))
            {
                return null;
            }

            if (weakRef != null && weakRef.IsAlive)
            {
                return weakRef.Target as T;
            }

            _cache.Remove(key);

            return null;
        }
        set
        {
            _cache[key] = new WeakReference(value);
        }
    }
}

这是我的测试:

    [TestMethod]
    public void TestCaching()
    {
        const string KEY = "test";

        GCManagedCache<byte[]> cache = new GCManagedCache<byte[]>();

        var o = new byte[1024];
        cache[KEY] = o;

        var y = cache[KEY];      // <-- seems to keep it alive even though it's nulled out after the next GC call.

        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);

        o = null;
        y = null;

        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);

        var x = cache[KEY];         // <--- returns a valid value when it should be null
        Assert.IsTrue(x == null);
    }

这是导致意外行为的行:

var y = cache[KEY];

在最终作业中使用该行:

var x = cache[KEY];

始终导致返回有效对象。如果我将作业删除到&#34; y&#34;,那么它会按预期工作。

0 个答案:

没有答案