C# MemoryCache Guide
In C#, the MemoryCache class can be used to implement caching functionality. Here is a simple example:
using System;
using System.Collections.Generic;
using System.Runtime.Caching;
class Program
{
static void Main()
{
// 创建一个MemoryCache实例
MemoryCache cache = MemoryCache.Default;
// 添加一个缓存项,键为"key",值为"value",缓存时间为10分钟
cache.Add("key", "value", DateTimeOffset.Now.AddMinutes(10));
// 从缓存中获取值
string cachedValue = cache.Get("key") as string;
if (cachedValue != null)
{
Console.WriteLine("Value from cache: " + cachedValue);
}
else
{
Console.WriteLine("Value not found in cache.");
}
// 移除缓存项
cache.Remove("key");
}
}
In the example above, we start by instantiating a MemoryCache object, then use the Add method to add a cache item to the cache, specifying the key, value, and expiration time. We then use the Get method to retrieve the value from the cache and output it. Finally, we use the Remove method to remove the cache item. This way, caching functionality can be easily implemented.