C# cache a MemoryCache using system.runtime.caching

A shortcut to the help class directly:

Blog.csdn.net/qq_36051316…

Reference Documents:

MSDN CacheItemPolicy.ChangeMonitors Property:

Docs.microsoft.com/zh-cn/dotne…

MSDN CacheItemPolicy.ChangeMonitors Property :

Docs.microsoft.com/zh-cn/dotne…

Without further ado, go straight to the core code:

private void CacheTest()
{
    ObjectCache cache = MemoryCache.Default;// Declare the cache class

    string myCache = cache["mycache"] as string;[] in our brackets is the name of the cache

    if (myCache == null)
    {
        CacheItemPolicy policy = new CacheItemPolicy();// This object can set the expiration time of the cache, associated objects, etc.

        policy.AbsoluteExpiration = DateTime.Now.AddSeconds(10);// Set expiration time to current time +10 seconds, after 10 seconds, the cached item will be removed
        
        myCache ="123";// The value we need to cache

        cache.Set("mycache", myCache, policy);// Insert the cache
    }

    var m = myCache;
}
Copy the code