代码之家  ›  专栏  ›  技术社区  ›  Ami

Invoke有时返回null,有时返回value

  •  0
  • Ami  · 技术社区  · 16 年前

    我正在开发一个asp.net MVC应用程序。

    因为我有几个方法要修饰,每个方法的逻辑都是相同的(检查是否存在于缓存中,如果不调用真正的getter并存储在缓存中),所以我写了如下内容:

    执行检查缓存中是否存在等常见逻辑的帮助器方法:

        public object CachedMethodCall(MethodInfo realMethod, params object[] realMethodParams)
        {
            object result = null;
            string cacheKey = CachingHelper.GenereateCacheKey(realMethod, realMethodParams);
    
            // check if cache contains key, if yes take data from cache, else invoke real service and cache it for future use.
            if (_CacheManager.Contains(cacheKey))
            {
                result = _CacheManager.GetData(cacheKey);
            }
            else
            {
                result = realMethod.Invoke(_RealService, realMethodParams);
    
                // TODO: currently cache expiration is set to 5 minutes. should be set according to the real data expiration setting.
                AbsoluteTime expirationTime = new AbsoluteTime(DateTime.Now.AddMinutes(5));
                _CacheManager.Add(cacheKey, result, CacheItemPriority.Normal, null, expirationTime);
            }
    
            return result;
        }
    

    这一切都很好,很可爱。在每个装饰方法中,我都有以下代码:

    StackTrace currentStack = new StackTrace();
    string currentMethodName = currentStack.GetFrame(0).GetMethod().Name;
    var result = (GeoArea)CachedMethodCall(_RealService.GetType().GetMethod(currentMethodName), someInputParam);
    return result;
    

    问题是,有时线路在哪里 realMethod.Invoke(...)

    谢谢:)

    1 回复  |  直到 6 年前
        1
  •  0
  •   Vahid Farahmandian    6 年前

    我想我通过如下更新代码成功地解决了这个问题:

        public object CachedMethodCall(MethodInfo realMethod, params object[] realMethodParams)
        {
            string cacheKey = CachingHelper.GenereateCacheKey(realMethod, realMethodParams);
    
            object result = _CacheManager.GetData(cacheKey);
    
            if (result == null)
            {
                result = realMethod.Invoke(_RealService, BindingFlags.InvokeMethod, null, realMethodParams, CultureInfo.InvariantCulture);
    
                // TODO: currently cache expiration is set to 5 minutes. should be set according to the real data expiration setting.
                AbsoluteTime expirationTime = new AbsoluteTime(DateTime.Now.AddMinutes(5));
                _CacheManager.Add(cacheKey, result, CacheItemPriority.Normal, null, expirationTime);
            }
    
            return result;
        }
    

    我注意到前一个 _CacheManager.Contains 调用有时返回true,即使缓存不包含数据。我怀疑线程导致了问题,但我不确定。。。