MemoryCache UpdateCallback not working

I am trying to create a pool of connections to a third-party API and the connections will expire at an interval if they are not used. When they expire, they must be disabled through a third-party API.

It turned out that MemoryCache (System.Runtime.Caching) would handle this. However, UpdateCallback behaves strangely.

A simple LINQPad example:

void Main()
{
    var cache = MemoryCache.Default;
    var policy = new CacheItemPolicy();
    policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(1);
    policy.UpdateCallback = Update;
    cache.Set("figkey", "fig", policy);

    Thread.Sleep(2000);

    object result = cache.Get("figkey");

    Console.WriteLine(result == null ? "null" : result);
}

public static void Update(CacheEntryUpdateArguments arguments)
{
    Console.WriteLine("got here");
}

If I run this, the output will be as follows:

fig

He does NOT conclude. "

If I comment on the line starting with policy.UpdateCallback, the output will be as follows:

null

What am I doing wrong?

If there is a better way to accomplish my task, I am open to alternative suggestions.

+5
source share
3 answers

, Thread.Sleep, , . , , :

var i = 0;
for (var j = 0; j < 10000000; j++)
{
    for (var k = 0; k < 1000000; k++)
        i++;
    i--;
}
Console.WriteLine(i);

.

+4

Console.ReadLine() Main Sleep with Console.ReadLine(), 10 . . MemoryCache .

, , MemoryCache : UpdateCallback , .

AbsoluteExpiration , Get null UpdateCallback.

BTW, RemovedCallback .

+1

, , .

The expiration occurs in another thread through a timer (you can see the same if you set a breakpoint in the callback). That's why sleeping or waiting works.

0
source

All Articles