MemoryCache does not obey memory limits in configuration

前端 未结 7 1124
暖寄归人
暖寄归人 2020-11-28 18:01

I’m working with the .NET 4.0 MemoryCache class in an application and trying to limit the maximum cache size, but in my tests it does not appear that the cache is actually o

7条回答
  •  时光取名叫无心
    2020-11-28 18:31

    I have done some testing with the example of @Canacourse and the modification of @woany and I think there are some critical calls that block the cleaning of the memory cache.

    public void CacheItemRemoved(CacheEntryRemovedArguments Args)
    {
        // this WriteLine() will block the thread of
        // the MemoryCache long enough to slow it down,
        // and it will never catch up the amount of memory
        // beyond the limit
        Console.WriteLine("...");
    
        // ...
    
        // this ReadKey() will block the thread of 
        // the MemoryCache completely, till you press any key
        Console.ReadKey();
    }
    

    But why does the modification of @woany seems to keep the memory at the same level? Firstly, the RemovedCallback is not set and there is no console output or waiting for input that could block the thread of the memory cache.

    Secondly...

    public void AddItem(string Name, string Value)
    {
        // ...
    
        // this WriteLine will block the main thread long enough,
        // so that the thread of the MemoryCache can do its work more frequently
        Console.WriteLine("...");
    }
    

    A Thread.Sleep(1) every ~1000th AddItem() would have the same effect.

    Well, it's not a very deep investigation of the problem, but it looks as if the thread of the MemoryCache does not get enough CPU time for cleaning, while many new elements are added.

提交回复
热议问题