的MemoryCache UpdateCallback不工作 [英] MemoryCache UpdateCallback not working

查看:226
本文介绍了的MemoryCache UpdateCallback不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建连接池,以第三方的API,并连接的时间间隔之后到期,如果他们不使用。过期时,他们需要经由第三方API来断开

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.

这似乎的MemoryCache(System.Runtime.Caching)将处理这个问题。 UpdateCallback似乎表现得奇怪的是,虽然。

It appeared that MemoryCache (System.Runtime.Caching) would handle this. UpdateCallback seems to behave oddly, though.

一个简单的LINQPad例如:

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

它确实不会输出来到这里。

如果我注释掉与 policy.UpdateCallback 开头的行,输出的是:

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.

推荐答案

我认为这个问题可能是 Thread.sleep代码,因为这也阻止缓存,因为他们在同一个线程中运行。如果你试图让虚拟的循环,你会本身的更新处理程序被触发:

I Think that the problem may be the Thread.Sleep because that also blocks the cache, as they run in the same thread. If you try to make dummy loops you will se that the update handler is triggered:

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

相反的睡眠。

Instead of the sleep.

这篇关于的MemoryCache UpdateCallback不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆