簡體   English   中英

從靜態方法讀取和寫入ASP.NET緩存

[英]Read and write to ASP.NET cache from static method

我在一個名為helper.getdiscount()的輔助類中有一個靜態方法。 此類是ASP.NET前端代碼,由UI頁面使用。

在這個方法中,我檢查一些數據是否在ASP.NET緩存中然后返回它,否則它進行服務調用並將結果存儲在緩存中,然后返回該值。

考慮到多個線程可能同時訪問它,這是一個問題嗎?

if (HttpContext.Current.Cache["GenRebateDiscountPercentage"] == null)
{ 
    IShoppingService service = ServiceFactory.Instance.GetService<IShoppingService>();
    rebateDiscountPercentage= service.GetGenRebateDiscountPercentage().Result;


    if (rebateDiscountPercentage > 0)
    {
        HttpContext.Current.Cache.Add("GenRebateDiscountPercentage", rebateDiscountPercentage, null, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
    }
}
else
{      
    decimal.TryParse(HttpContext.Current.Cache["GenRebateDiscountPercentage"].ToString(), out rebateDiscountPercentage);
}

請告知是否正常或可以使用更好的方法。

用lock對象嘗試這樣的東西。

static readonly object objectToBeLocked= new object();

        lock( objectToBeLocked)
        { 
             if (HttpContext.Current.Cache["GenRebateDiscountPercentage"] == null)
            { 
                IShoppingService service = ServiceFactory.Instance.GetService<IShoppingService>();
                rebateDiscountPercentage= service.GetGenRebateDiscountPercentage().Result;


                if (rebateDiscountPercentage > 0)
                {
                    HttpContext.Current.Cache.Add("GenRebateDiscountPercentage", rebateDiscountPercentage, null, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
                }
            }
            else
            {      
                decimal.TryParse(HttpContext.Current.Cache["GenRebateDiscountPercentage"].ToString(), out rebateDiscountPercentage);
            }
        }

您也可以查看以下主題。

在asp.net中鎖定緩存的最佳方法是什么?

使用這些通用方法可以將緩存用於任何類型:

`public static void AddCache(string key, object Data, int minutesToLive = 1440)
{
    if (Data == null)
        return;
    HttpContext.Current.Cache.Insert(key, Data, null, DateTime.Now.AddMinutes(minutesToLive), Cache.NoSlidingExpiration);
}

public static T GetCache<T>(string key)
{
    return (T)HttpContext.Current.Cache.Get(key);
} `

現在來解決你的問題:

`if(GetCache<decimal>("GenRebateDiscountPercentage") == null)
{ 

   IShoppingService service = ServiceFactory.Instance.GetService<IShoppingService>();
   rebateDiscountPercentage= service.GetGenRebateDiscountPercentage().Result;


   if (rebateDiscountPercentage > 0)
   {
       AddCache("GetGenRebateDiscountPercentage", rebateDiscountPercentage);
   }
}
else
{
    rebateDiscountPercentage = GetCache<decimal>("GetGenRebateDiscountPercentage");
}

`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM