Monday, October 7, 2019

c# - Memory Cache example and call to async method.


  public static T GetRestObjectFromServiceOrCache<T>(string cacheItemName, Func<int, T> objectMethod, int id)
        {
            var expiration = CommonFactory.GetSettingsPage().RewardCategoryCacheTime == 0 ? DateTime.Now.AddHours(24) : DateTime.Now.AddHours(CommonFactory.GetSettingsPage().RewardCategoryCacheTime);

            ObjectCache cache = MemoryCache.Default;
            var cachedObject = (T)cache[cacheItemName];
            if (cachedObject == null)
            {
                CacheItemPolicy policy = new CacheItemPolicy
                {
                    AbsoluteExpiration = expiration
                };
                cachedObject = objectMethod(id);
                cache.Set(cacheItemName, cachedObject, policy);
            }

            return cachedObject;
        }
And Use it with this:
 var rewards = Task.Run(async () => await RestApiHelper.GetShopGroup(RestApiHelper.PartnerSe, id)).Result;

No comments:

Post a Comment