如何使用Timer插入的MemoryCache触发方法? [英] How to use MemoryCache insted of Timer to trigger a method?

查看:105
本文介绍了如何使用Timer插入的MemoryCache触发方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下方法通过等待已经运行的操作的结果来处理并发请求.

The following method handle concurrent request by waiting the result of an already running operation.

对数据的请求可能同时具有相同/不同的凭据.对于每组唯一的凭据,最多只能进行一个GetCurrentInternal调用,并且该调用的结果将在准备就绪时返回给所有排队的服务员.

Requests for data may come in simultaneously with same/different credentials. For each unique set of credentials there can be at most one GetCurrentInternal call in progress, with the result from that one call returned to all queued waiters when it is ready.

private readonly ConcurrentDictionary<Credentials, Lazy<Data>> _dataToCredentialMap =
        new ConcurrentDictionary<Credentials, Lazy<Data>>();

public virtual Data GetCurrent(Credentials credentials)
{
    if (credentials == null) { return GetCurrentInternal(null); }

    // It will only allow a single call to GetCurrentInternal, even if multiple threads query its Value property simultaneously.
    var lazyData = new Lazy<Data>(() => GetCurrentInternal(credentials));

    var data = _dataToCredentialMap.GetOrAdd(credentials, lazyData);
    return data.Value;
}

我在构造函数的此类中添加了timer.这是基于时间的失效策略,在该时间段内,缓存条目会在明确定义的一段时间后自动失效.

And I have added timer inside of this class in constructor. It's time-based invalidation policy where cache entries are auto-invalidated after a certain well-defined period of time.

_dataUpdateTimer = new Timer(UpdateData, null, TimeSpan.Zero, _dataUpdateInterval); // 1 min

更新数据的方法如下所示:

Method that update data looks like the following:

private void UpdateData(object notUsed)
{
    try
    {
        foreach (var credential in _dataToCredentialMap.Keys)
        {
            var data = new Lazy<Data>(() => GetCurrent(credential));
            _dataToCredentialMap.AddOrUpdate(credential, data, (k, v) => data);
        }
     }
     catch (Exception ex)
     {
          _logger.WarnException(ex, "Failed to update agent metadata");
     }
}

我想使用由ConcurrentDictionaryTimer插入的.net MemoryCache类更新我的Credential and Data,我认为这样会更高效.

I would like to use .Net MemoryCache class insted of my ConcurrentDictionary and Timer, to update my Credential and Data I think it will be more efficient.

我知道如何使用MemoryCache代替ConcurrentDictionary,但是如何在没有Timer的情况下在构造函数中每分钟调用UpdateData?

I know how I can use MemoryCache instead of ConcurrentDictionary, but how can I call UpdateData each minute in constructor without a Timer?

您能帮我怎么做吗?

推荐答案

您可以在不使用计时器的情况下使用MemoryCache进行此操作.只需将CacheItemPolicy设置为AbsoluteExpiration:

You can do this with MemoryCache without a Timer. Just set the CacheItemPolicy to AbsoluteExpiration:

MemoryCache memCache = MemoryCache.Default;
memCache.Add(<mykey>, <myvalue>,
          new CacheItemPolicy()
          {
            AbsoluteExpiration = DateTimeOffset.Now.Add(TimeSpan.FromMinutes(_expireminutes)),
            SlidingExpiration = new TimeSpan(0, 0, 0)
          }
          );

这篇关于如何使用Timer插入的MemoryCache触发方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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