Doing locking in ASP.NET correctly

后端 未结 3 726
广开言路
广开言路 2020-12-29 14:40

I have an ASP.NET site with a fairly slow search function, and I want to improve performance by adding the results to the cache for one hour using the query as the cache-key

3条回答
  •  孤独总比滥情好
    2020-12-29 15:17

    Your code is correct. You are also using double-if-sandwitching-lock which will prevent race conditions which is a common pitfall when not used. This will no lock access to existing stuff in the cache.

    The only problem is when many clients are inserting into the cache at the same time, and they will queue behind the lock but what I would do is to put the results = GetResultsFromSlowDb(query); outside the lock:

    public static string DoSearch(string query)
    {
        string results = "";
    
        if (HttpContext.Current.Cache[query] == null)
        {
            results = GetResultsFromSlowDb(query); // HERE
            lock (_cacheLock)
            {
                if (HttpContext.Current.Cache[query] == null)
                {
    
    
                    HttpContext.Current.Cache.Add(query, results, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
                }
                else
                {
                    results = HttpContext.Current.Cache[query].ToString();
                }
            }
        }
        else
        {
            results = HttpContext.Current.Cache[query].ToString();
        }
    

    If this is slow, your problem is elsewhere.

提交回复
热议问题