Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Completely Unable to Define the UpdateCallback of System.Runtime.Caching

Tags:

c#

.net

caching

I'm having a difficult time using the CacheEntryUpdateCallback delegate of the System.Runtime.Caching library. Whenever I define and set the callback, I get an ArgumentException that the "CacheItemUpdateCallback must be null". Why must it be null? I should be able to set this and then get the callback.

I do not get this when using the CacheEntryRemovedCallback delegate. I can reliably reproduce this in all of my projects. Am I doing something wrong? Here's a small sample application:

using System.Runtime.Caching;
class Program {
  static void Main(string[] args) {
    var policy = new CacheItemPolicy();
    policy.SlidingExpiration = TimeSpan.FromSeconds(10);

    // this works
    //policy.RemovedCallback = Removed;

    // this creates the exception
    policy.UpdateCallback = Update;

    MemoryCache.Default.Add("test", "123", policy);
    Console.Read();
  }

  static void Update(CacheEntryUpdateArguments arguments) { }
  static void Removed(CacheEntryRemovedArugments arguments) { }
}
like image 705
Chris Avatar asked Feb 10 '15 16:02

Chris


People also ask

What is a runtime cache?

Runtime caching refers to gradually adding responses to a cache "as you go". While runtime caching doesn't help with the reliability of the current request, it can help make future requests for the same URL more reliable.

What is Memorycache C#?

In-Memory Cache is used for when you want to implement cache in a single process. When the process dies, the cache dies with it. If you're running the same process on several servers, you will have a separate cache for each server. Persistent in-process Cache is when you back up your cache outside of process memory.


1 Answers

According to documentation you should be using Set instead of Add.

MemoryCache.Add:

The Add and AddOrGetExisting method overloads do not support the UpdateCallback property. Therefore, to set the UpdateCallback property for a cache entry, use the Set method overloads instead.

Following indeed work without problems:

MemoryCache.Default.Set("test", "123", policy);
like image 88
Alexei Levenkov Avatar answered Oct 22 '22 23:10

Alexei Levenkov