Locking pattern for proper use of .NET MemoryCache

前端 未结 9 2106
栀梦
栀梦 2020-11-30 17:13

I assume this code has concurrency issues:

const string CacheKey = \"CacheKey\";
static string GetCachedData()
{
    string expensiveString =null;
    if (Me         


        
9条回答
  •  悲哀的现实
    2020-11-30 17:52

    Console example of MemoryCache, "How to save/get simple class objects"

    Output after launching and pressing Any key except Esc :

    Saving to cache!
    Getting from cache!
    Some1
    Some2

        class Some
        {
            public String text { get; set; }
    
            public Some(String text)
            {
                this.text = text;
            }
    
            public override string ToString()
            {
                return text;
            }
        }
    
        public static MemoryCache cache = new MemoryCache("cache");
    
        public static string cache_name = "mycache";
    
        static void Main(string[] args)
        {
    
            Some some1 = new Some("some1");
            Some some2 = new Some("some2");
    
            List list = new List();
            list.Add(some1);
            list.Add(some2);
    
            do {
    
                if (cache.Contains(cache_name))
                {
                    Console.WriteLine("Getting from cache!");
                    List list_c = cache.Get(cache_name) as List;
                    foreach (Some s in list_c) Console.WriteLine(s);
                }
                else
                {
                    Console.WriteLine("Saving to cache!");
                    cache.Set(cache_name, list, DateTime.Now.AddMinutes(10));                   
                }
    
            } while (Console.ReadKey(true).Key != ConsoleKey.Escape);
    
        }
    

提交回复
热议问题