简体   繁体   中英

ASP.NET cache issue

I'm caching MyData to avoid unnecessary calls to web service but it seems there is some problem. It is possible that caching is working correctly but I failed to figure out what causes problems. This is how I cache my data. I use static cache helper. You can google "cache helper c#" if you need that piece of code.

     private static object locker = new object();
    private static List<SomeDataDto> myData;
    private static List<SomeDataDto> MyData{
        get{
            if (CacheHelper.Exists("MyData") == false){
                lock (locker){

                    if (CacheHelper.Exists("MyData") == true){
                        myData=(List<SomeDataDto>)CacheHelper.GetCacheObject("MyData");
                    }
                    else
                    if (CacheHelper.Exists("MyData") == false){
                        var myData = GetSomethingFromDatabase("en", true);
                    CacheHelper.Add(myData, "MyData", 360);
                }
            }
            }
            return (List<SomeDataDto>)CacheHelper.GetCacheObject("MyData");
        }
    }

I'm calling this method on my page and this method throws error (sometimes!)

  public SomeObjectToReturn GetOneItem(string language, string id)
    {

        return MyData.Where(x => x.Language == language.ToUpper()).SelectMany(x => x.Something).SelectMany(x => x.SomethingElse).Where(x => x.ID == id).FirstOrDefault();
    }

I call this method 15 times for 15 different id-s but it works for 10 items or 8 items or something like that. If I edit config to remove cache some other id-s are not working. So:

  1. First time it works id=6
  2. Second time it doesn't work id=6

Is it cache corrupted? Web Service does not return all elements in list? (too many of them?)

You have to include your return (List)CacheHelper.GetCacheObject("MyData"); in your lock like:

    get{
        lock (locker){
           if (CacheHelper.Exists("MyData") == false){

                if (CacheHelper.Exists("MyData") == true){
                    myData=(List<SomeDataDto>)CacheHelper.GetCacheObject("MyData");
                }
                else
                if (CacheHelper.Exists("MyData") == false){
                    var myData = GetSomethingFromDatabase("en", true);
                CacheHelper.Add(myData, "MyData", 360);
            }
          }
         return (List<SomeDataDto>)CacheHelper.GetCacheObject("MyData");
       }
    }

If you read while you are writing or deleting the behavior could be different as you expect. The List object is not thread safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM