4

在一个理智的世界中,我会期望该UpdateCallBack属性会增加我的参数集合。但事实并非如此:在此测试的最后一行中,updateArguments集合预计为 3(每次Set调用两次,调用一次Remove),但它是空的。

测试是粗略的和准备好的,但它应该足以说明正在发生一些奇怪的事情。

或者我遗漏了一些明显的东西。

编辑:这越来越陌生。基于这个问题MemoryCache UpdateCallback not working,它说Thread.Sleep阻止MemoryCache.Default对象,我将原始Thread.Sleep(5000)调用更改为Task.Factory.StartNew(() => Thread.Sleep(10000)).Wait();. 然后,如果我注释掉对 的调用MemoryCache.Default.Remove()updateArguments集合确实会增加,但只会增加一次,那就是"PersonKey"缓存项过期的时候。两个Set()和一个Remove()呼叫被完全忽略。我有一个“见鬼”的时刻。

[Test]
public void TheMemoryCacheMaintainsAMemberAndInvokesTheUpdateCallback()
{
    var person = new Person { GivenName = "Rob", LastName = "Lyndon"};
    var givenName = person.GivenName;
    var lastName = person.LastName;

    var updateArguments = new List<CacheEntryUpdateArguments>();

    MemoryCache.Default.Set("PersonKey", person, CreateNewPolicy(updateArguments));
    var cachedItem = MemoryCache.Default.Get("PersonKey") as Person;
    Assert.IsNotNull(cachedItem);
    Assert.That(cachedItem.GivenName, Is.EqualTo(givenName));
    Assert.That(cachedItem.LastName, Is.EqualTo(lastName));

    person.LastName = "Lyndon - Updated";
    MemoryCache.Default.Set("PersonKey", member, CreateNewPolicy(updateArguments));
    cachedItem = MemoryCache.Default.Get("PersonKey") as Person;
    Assert.IsNotNull(cachedItem);
    Assert.That(cachedItem.GivenName, Is.EqualTo(givenName));
    Assert.That(cachedItem.LastName, Is.EqualTo(lastName + " - Updated"));

    Task.Factory.StartNew(() => Thread.Sleep(10000)).Wait();
    Thread.Sleep(5000);
    Assert.That(updateArguments.Count, Is.EqualTo(3));
}

private static CacheItemPolicy CreateNewPolicy(ICollection<CacheEntryUpdateArguments> updateArguments)
{
    return new CacheItemPolicy
        {
            AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(1),
            UpdateCallback = args => updateArguments.Add(args)
        };
}
4

0 回答 0