I'm trying to create a pool of connections to a third-party API, and have connections expire after an interval if they are not in use. When they expire, they need to be disconnected via the third-party API.
It appeared that MemoryCache (System.Runtime.Caching) would handle this. UpdateCallback seems to behave oddly, though.
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 is:
fig
It does NOT output "got here".
If I comment out the line that starts with policy.UpdateCallback
, the output is:
null
What am I doing wrong?
If there's a better way to accomplish my task, I'm open to alternative suggestions.