当前位置:网站首页>Use of cache in C #
Use of cache in C #
2022-07-24 20:57:00 【biyusr】
brief introduction
Cache refers to the memory that can exchange high-speed data , It precedes memory and CPU Exchange data , So the speed is very fast . because CPU Reading data from memory is several orders of magnitude faster than reading data from disk , And it's in memory , Reduce the pressure of database access , So caching is used in almost every project . Commonly used are MemoryCache、Redis Today I will bring you MemoryCache Introduction to the use of !
Category
Memory cache expiration time is 4 Kind of
• Never expire • Absolute expiration time • Relative to the current expiration time • Slide expiration time
Of course, it can also be derived from these three expiration times The sliding window + Absolute expiration time, etc
Official website address
We can also check the official documents To learn more about MemoryCache I won't read too much here
•MemoryCache Address
Use
Go back to the question Let's introduce how to set the expiration time !
Never expire
After my program is released, as long as we don't clean up the cache , The cache will remain valid !
/// <summary>
/// Never expire
/// </summary>
static void NeverExpire()
{
_cache.Set("NeverExpire", "1");
}Absolute expiration time
In absolute time Can be interpreted as " Closing date "
static void AbsoluteExpiration()
{
DateTime time = new DateTime(2022, 04, 01, 23, 59, 59);
_cache.Set("AbsoluteExpiration", "20220401235959", time);
}Relative to the current expiration time
Relative to the current expiration time , For example, it is valid within one minute after we set the cache , You can refer to our common SMS login , The back-end randomly generates a verification code and stores it in redis, And set the key The expiration time of , And then there's verification , Send mobile phone number and verification code to the background , from redis Take out the corresponding verification code and check it , If correct, delete the captcha , Prevent multiple verifications
static void ExpirationTimeRelativeToThePresent()
{
_cache.Set("AbsoluteExpiration", "123456", new TimeSpan(0, 0, 60));
}Slide expiration time
The cache is not used within the set time , Failure , After use, the expiration time of the cache is refreshed again
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 figure !
Then explain the second parameter MemoryCacheEntryOptions, Set the absolute expiration date of the cache item : Is after the current cache setting 1000 minute . Like the hero League mobile game we often play , We don't log in for a day , The cache token invalid , You have to log in again to get token, Every day we're out of time to play , You don't need to start every time app Login account at , however After playing for a while , It is found that we still need to log in to our account again. This is the absolute expiration time in the sliding expiration time !
Get cache value
ConcurrentDictionary<object, CacheEntry> _entries: A multi thread safe dictionary type , In fact, the essence of cache is this dictionary , Put all caches into this dictionary , Then through the dictionary key( Dictionary key In fact, it is similar to caching entities CacheEntry Of key Have the same value ) obtain CacheEntry Entity (CacheEntry Entity contains key and value, That's what we set in our code key and value).
static void GetCache()
{
// Mode one
_cache.Get("NeverExpire").ToString();
// Mode two
string value = "";
if (!_cache.TryGetValue("NeverExpire", out value))
{
throw new Exception(" The cache does not exist or has expired ");
}
}Clear cache value
static void GetCache()
{
string value = "";
if (_cache.TryGetValue("NeverExpire", out value))
{
_cache.Remove("NeverExpire");
}
}Maybe you found out , We don't need to... When we remove it value value , Then use temporary variables , Is it a little painful !
Actually C# It's also taken into account , that c# from 7.0 Start to support abandonment , Abandoning yuan is not just a written and semantic improvement , It can also reduce 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(" The cache does not exist or has expired ");
}
if (_cache.TryGetValue("NeverExpire", out value))
{
_cache.Remove("NeverExpire");
}
if (_cache.TryGetValue("NeverExpire", out _))
{
_cache.Remove("NeverExpire");
}
}
/// <summary>
/// Never expire
/// </summary>
static void NeverExpire()
{
_cache.Set("NeverExpire", "1");
}
/// <summary>
/// Absolute expiration time
/// </summary>
static void AbsoluteExpiration()
{
DateTime time = new DateTime(2022, 04, 01, 23, 59, 59);
_cache.Set("AbsoluteExpiration", "20220401235959", time);
}
/// <summary>
/// Relative to the current expiration time
/// </summary>
///
static void ExpirationTimeRelativeToThePresent()
{
_cache.Set("AbsoluteExpiration", "123456", new TimeSpan(0, 0, 60));
}
/// <summary>
/// Slide expiration time
/// </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 praise , hope net The ecosystem is getting better and better !
边栏推荐
- [basic data mining technology] KNN simple clustering
- Oracle primary key auto increment setting
- Preview and save pictures using uni app
- Summary of yarn capacity scheduler
- [training Day10] linear [mathematics] [thinking]
- Evolution of network IO model
- What should Ali pay attention to during the interview? Personal account of Alibaba interns who passed five rounds of interviews
- When using vscode, the tab indentation changes from 4 spaces to small arrows (solved)
- One bite of Stream(6)
- [summary of Feature Engineering] explain what features are and the steps of feature engineering
猜你喜欢

Actual measurement of Qunhui 71000 Gigabit Network

C WinForm actual operation XML code, including the demonstration of creating, saving, querying and deleting forms

What does software testing need to learn?

Pychart tutorial: 5 very useful tips

API data interface of A-share transaction data
![[training Day9] rotate [violence] [thinking]](/img/b9/598dd0dffb9c82230f43484f9c8a1e.png)
[training Day9] rotate [violence] [thinking]

what? Does the multi merchant system not adapt to app? This is coming!
![[Extension Program - cat scratch 1.0.15 _ online video and audio acquisition artifact _ installation tutorial plus acquisition]](/img/75/5eca7f63758802ecf86a90a1bbdeaf.png)
[Extension Program - cat scratch 1.0.15 _ online video and audio acquisition artifact _ installation tutorial plus acquisition]

Software testing interview tips | if you don't receive the offer, I'll wash my hair upside down

Smarter! Airiot accelerates the upgrading of energy conservation and emission reduction in the coal industry
随机推荐
Defects of matrix initialization
Luogu - p1616 crazy herb picking
How to use named slots
API data interface of A-share transaction data
驱动子系统开发
[JVM] selection of garbage collector
[training Day10] silly [simulation] [greed]
The difference between map and flatmap in stream
1. Mx6u-alpha development board (key input experiment)
Summary of yarn capacity scheduler
Detailed explanation of ThreadLocal
[training Day8] interesting number [digital DP]
Bring new people's experience
Opencv learning Day2
Modulenotfounderror: no module named 'pysat.solvers' (resolved)
RESNET interpretation and 1 × 1 Introduction to convolution
Baidu classic interview question - determine prime (how to optimize?)
Unity's ugui text component hard row display (improved)
Do you want to enroll in a training class or study by yourself?
Inconsistent time
