当前位置:网站首页>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 !
边栏推荐
- Rhodamine B labeled PNA | rhodamine b-pna | biotin modified PNA | biotin modified PNA | specification information
- Shengbang security rushes to the scientific innovation board: Qianxin is its largest customer (55.87 million); Its three-year revenue is 460 million, net profit is 95.04 million, and R & D investment
- [training Day6] triangle [mathematics] [violence]
- The difference between map and flatmap in stream
- API data interface for historical data of A-share index
- Applet wonderful bug update~
- 93. Recursive implementation of combinatorial enumeration
- How does starknet change the L2 landscape?
- RESNET interpretation and 1 × 1 Introduction to convolution
- Native applets are introduced using vant webapp
猜你喜欢

Eight transformation qualities that it leaders should possess

Drive subsystem development

Alibaba Sentinel 基操
![[training Day8] interesting number [digital DP]](/img/39/caad2ccff916d5ab0f8c3d93f3901d.png)
[training Day8] interesting number [digital DP]

One bite of Stream(7)

Actual measurement of Qunhui 71000 Gigabit Network

Lecun proposed that mask strategy can also be applied to twin networks based on vit for self supervised learning!

Baidu PaddlePaddle easydl helps improve the inspection efficiency of high-altitude photovoltaic power stations by 98%

Evolution of network IO model
![[feature construction] construction method of features](/img/5c/c240d9d742f37cbc52afecf15b2ad1.png)
[feature construction] construction method of features
随机推荐
Selenium is detected as a crawler. How to shield and bypass it
[msp430g2553] graphical development notes (1) configuration environment
Merge sort
The maximum number of expressions in ora-01795 list is 1000
驱动子系统开发
Synthesis of peptide nucleic acid PNA labeled with heptachydrin dye cy7 cy7-pna
(posted) differences and connections between beanfactory and factorybean
Career development suggestions shared by ten CIOs
Go language structure
Two methods of how to export asynchronous data
ECCV 2022 open source | target segmentation for 10000 frames of video
[training Day10] point [enumeration] [bidirectional linked list]
How to learn automated testing
2787: calculate 24
[basic data mining technology] exploratory data analysis
Modulenotfounderror: no module named 'pysat.solvers' (resolved)
1. Mx6u-alpha development board (buzzer experiment)
Azide labeled PNA peptide nucleic acid | methylene blue labeled PNA peptide nucleic acid | tyrosine modified PNA | Tyr PNA Qiyue Bio
96. Strange tower of Hanoi
[JVM] selection of garbage collector
