profile
Cache refers to a memory that can be exchanged at high speed. It exchanges data with the CPU before memory, so the speed is very fast. Because the CPU reads data from memory several orders of magnitude faster than reading from disk, and it is stored in memory, reducing the pressure on database access, caching is used for almost every item. Commonly used ones are MemoryCache and Redis. Today I will bring you an introduction to the use of MemoryCache!
category
There are 4 memory cache expiration times
- never expires
- Absolute expiration time
- Relative to the current expiration time
- Sliding expiration time
Of course, you can also use these three expiration times to derive a sliding window + absolute expiration time, etc.
official website address
We can also check the official documentation to learn more about MemoryCache, so we won't explain too much here.
- MemoryCache 地址: https://docs.microsoft.com/zh-cn/dotnet/api/system.runtime.caching.memorycache?redirectedfrom=MSDN&view=dotnet-plat-ext-6.0
use
Back to the question just now, let's introduce how to set the expiration time!
never expires
That is, as long as we don't clean up the cache after my program is released, the cache will remain effective!
/// <summary>
/// 永不过期时间
/// </summary>
static void NeverExpire()
{
_cache.Set("NeverExpire", "1");
}
Absolute expiration time
Absolute time points are used, which can be understood as "deadline"
static void AbsoluteExpiration()
{
DateTime time = new DateTime(2022, 04, 01, 23, 59, 59);
_cache.Set("AbsoluteExpiration", "20220401235959", time);
}
Relative to the current expiration time
Compared with the current expiration time, for example, it is effective within one minute after we set the cache. You can refer to our common SMS login. The backend randomly generates a Captcha and stores it in redis, and sets the expiration time of the key. Then it is verified. Send the mobile phone number and Captcha to the background, and take out the corresponding Captcha from redis to verify it. If it is correct, delete the Captcha to prevent verification multiple times
static void ExpirationTimeRelativeToThePresent()
{
_cache.Set("AbsoluteExpiration", "123456", new TimeSpan(0, 0, 60));
}
Sliding expiration time
If the cache is not used within the set time, it will expire, and the expiration time of the cache will be refreshed again after use
static void SlidingExpirationTime()
{
_cache.Set("SlidingExpirationTime", "3", new MemoryCacheEntryOptions()
{
SlidingExpiration = new TimeSpan(0, 0, 2),
AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(1000)
});
}
Let's take a look at the definition of the official website as shown in the picture!

Then let's explain the second parameter, MemoryCacheEntryOptions, which sets the absolute expiration date of the cache entry: 1000 seconds after the current cache setting (perhaps minutes? Just kidding, normal scenarios usually take 5 minutes, 10 minutes, etc., depending on the actual business design). Like the League of Legends mobile game we often play, we don't log in for a day, and if the cached token expires, we have to log in again to get a token. We play every day and trigger a sliding expiration time, so we don't need to log in to our account every time we launch the app, but after playing for a while, we found that we still need to log in to our account again. This is the absolute expiration time of the sliding expiration time!
Get cached value
ConcurrentDictionary<object, CacheEntry> _entries: A multi-threaded safe dictionary type. In fact, the essence of caching is this dictionary. Put all caches into this dictionary, and then obtain the CacheEntry entity through the key of the dictionary (the key of the dictionary is actually the same as the key value of the cache entity CacheEntry)(the CacheEntry entity contains the key and value, which is the key and value set in our code).
static void GetCache()
{
//方式一
_cache.Get("NeverExpire").ToString();
//方式二
string value = "";
if (!_cache.TryGetValue("NeverExpire", out value))
{
throw new Exception("不存在该缓存或者已过期");
}
}
Clear cache value
static void GetCache()
{
string value = "";
if (_cache.TryGetValue("NeverExpire", out value))
{
_cache.Remove("NeverExpire");
}
}
You may have noticed that we don't need the value value at all when removing it, so it's a bit painful to use temporary variables again!
In fact, C#has also taken this issue into account, so C#has supported abandonment since 7.0. Abandonment is not only a writing and semantic improvement, but also reduces memory allocation.
Simplify the above code
static void GetCache()
{
if (_cache.TryGetValue("NeverExpire", out _))
{
_cache.Remove("NeverExpire");
}
}
complete code
class Program
{
public static IMemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
static void Main(string[] args)
{
_cache.Get("NeverExpire").ToString();
string value = "";
if (!_cache.TryGetValue("NeverExpire", out value))
{
throw new Exception("不存在该缓存或者已过期");
}
if (_cache.TryGetValue("NeverExpire", out value))
{
_cache.Remove("NeverExpire");
}
if (_cache.TryGetValue("NeverExpire", out _))
{
_cache.Remove("NeverExpire");
}
}
/// <summary>
/// 永不过期时间
/// </summary>
static void NeverExpire()
{
_cache.Set("NeverExpire", "1");
}
/// <summary>
/// 绝对过期时间
/// </summary>
static void AbsoluteExpiration()
{
DateTime time = new DateTime(2022, 04, 01, 23, 59, 59);
_cache.Set("AbsoluteExpiration", "20220401235959", time);
}
/// <summary>
/// 相对现在的过期时间
/// </summary>
///
static void ExpirationTimeRelativeToThePresent()
{
_cache.Set("AbsoluteExpiration", "123456", new TimeSpan(0, 0, 60));
}
/// <summary>
/// 滑动过期时间
/// </summary>
static void SlidingExpirationTime()
{
_cache.Set("key3", "3", new MemoryCacheEntryOptions()
{
SlidingExpiration = new TimeSpan(0, 0, 2),
AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(1000)
});
}
}
Finally, if you like my article, please pay attention and like it, hoping that the net ecosystem will get better and better!