- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我需要添加缓存功能并找到了一个名为 MemoryCache 的新类。但是,我发现 MemoryCache 有点残缺(我需要区域功能)。除其他事项外,我需要添加类似 ClearAll(region) 的内容。作者努力让这个类没有区域支持,代码如下:
if (regionName != null)
{
throw new NotSupportedException(R.RegionName_not_supported);
}
几乎适用于所有方法。我没有看到一种简单的方法来覆盖这种行为。我能想到的添加区域支持的唯一方法是添加一个新类作为 MemoryCache 的包装器,而不是作为继承自 MemoryCache 的类。然后在这个新类中创建一个字典并让每个方法“缓冲”区域调用。听起来很糟糕而且是错误的,但最终……
您知道将区域添加到 MemoryCache 的更好方法吗?
最佳答案
我知道你问这个问题已经很久了,所以这并不是真正的答案,而是对 future 读者的补充。
我还惊讶地发现 MemoryCache 的标准实现不支持区域。马上提供会很容易。因此,我决定将 MemoryCache 包装在我自己的简单类中,以提供我经常需要的功能。
我在这里附上我的代码,以节省其他有相同需求的人的时间!
/// <summary>
/// =================================================================================================================
/// This is a static encapsulation of the Framework provided MemoryCache to make it easier to use.
/// - Keys can be of any type, not just strings.
/// - A typed Get method is provided for the common case where type of retrieved item actually is known.
/// - Exists method is provided.
/// - Except for the Set method with custom policy, some specific Set methods are also provided for convenience.
/// - One SetAbsolute method with remove callback is provided as an example.
/// The Set method can also be used for custom remove/update monitoring.
/// - Domain (or "region") functionality missing in default MemoryCache is provided.
/// This is very useful when adding items with identical keys but belonging to different domains.
/// Example: "Customer" with Id=1, and "Product" with Id=1
/// =================================================================================================================
/// </summary>
public static class MyCache
{
private const string KeySeparator = "_";
private const string DefaultDomain = "DefaultDomain";
private static MemoryCache Cache
{
get { return MemoryCache.Default; }
}
// -----------------------------------------------------------------------------------------------------------------------------
// The default instance of the MemoryCache is used.
// Memory usage can be configured in standard config file.
// -----------------------------------------------------------------------------------------------------------------------------
// cacheMemoryLimitMegabytes: The amount of maximum memory size to be used. Specified in megabytes.
// The default is zero, which indicates that the MemoryCache instance manages its own memory
// based on the amount of memory that is installed on the computer.
// physicalMemoryPercentage: The percentage of physical memory that the cache can use. It is specified as an integer value from 1 to 100.
// The default is zero, which indicates that the MemoryCache instance manages its own memory
// based on the amount of memory that is installed on the computer.
// pollingInterval: The time interval after which the cache implementation compares the current memory load with the
// absolute and percentage-based memory limits that are set for the cache instance.
// The default is two minutes.
// -----------------------------------------------------------------------------------------------------------------------------
// <configuration>
// <system.runtime.caching>
// <memoryCache>
// <namedCaches>
// <add name="default" cacheMemoryLimitMegabytes="0" physicalMemoryPercentage="0" pollingInterval="00:02:00" />
// </namedCaches>
// </memoryCache>
// </system.runtime.caching>
// </configuration>
// -----------------------------------------------------------------------------------------------------------------------------
/// <summary>
/// Store an object and let it stay in cache until manually removed.
/// </summary>
public static void SetPermanent(string key, object data, string domain = null)
{
CacheItemPolicy policy = new CacheItemPolicy { };
Set(key, data, policy, domain);
}
/// <summary>
/// Store an object and let it stay in cache x minutes from write.
/// </summary>
public static void SetAbsolute(string key, object data, double minutes, string domain = null)
{
CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(minutes) };
Set(key, data, policy, domain);
}
/// <summary>
/// Store an object and let it stay in cache x minutes from write.
/// callback is a method to be triggered when item is removed
/// </summary>
public static void SetAbsolute(string key, object data, double minutes, CacheEntryRemovedCallback callback, string domain = null)
{
CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(minutes), RemovedCallback = callback };
Set(key, data, policy, domain);
}
/// <summary>
/// Store an object and let it stay in cache x minutes from last write or read.
/// </summary>
public static void SetSliding(object key, object data, double minutes, string domain = null)
{
CacheItemPolicy policy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(minutes) };
Set(key, data, policy, domain);
}
/// <summary>
/// Store an item and let it stay in cache according to specified policy.
/// </summary>
/// <param name="key">Key within specified domain</param>
/// <param name="data">Object to store</param>
/// <param name="policy">CacheItemPolicy</param>
/// <param name="domain">NULL will fallback to default domain</param>
public static void Set(object key, object data, CacheItemPolicy policy, string domain = null)
{
Cache.Add(CombinedKey(key, domain), data, policy);
}
/// <summary>
/// Get typed item from cache.
/// </summary>
/// <param name="key">Key within specified domain</param>
/// <param name="domain">NULL will fallback to default domain</param>
public static T Get<T>(object key, string domain = null)
{
return (T)Get(key, domain);
}
/// <summary>
/// Get item from cache.
/// </summary>
/// <param name="key">Key within specified domain</param>
/// <param name="domain">NULL will fallback to default domain</param>
public static object Get(object key, string domain = null)
{
return Cache.Get(CombinedKey(key, domain));
}
/// <summary>
/// Check if item exists in cache.
/// </summary>
/// <param name="key">Key within specified domain</param>
/// <param name="domain">NULL will fallback to default domain</param>
public static bool Exists(object key, string domain = null)
{
return Cache[CombinedKey(key, domain)] != null;
}
/// <summary>
/// Remove item from cache.
/// </summary>
/// <param name="key">Key within specified domain</param>
/// <param name="domain">NULL will fallback to default domain</param>
public static void Remove(object key, string domain = null)
{
Cache.Remove(CombinedKey(key, domain));
}
#region Support Methods
/// <summary>
/// Parse domain from combinedKey.
/// This method is exposed publicly because it can be useful in callback methods.
/// The key property of the callback argument will in our case be the combinedKey.
/// To be interpreted, it needs to be split into domain and key with these parse methods.
/// </summary>
public static string ParseDomain(string combinedKey)
{
return combinedKey.Substring(0, combinedKey.IndexOf(KeySeparator));
}
/// <summary>
/// Parse key from combinedKey.
/// This method is exposed publicly because it can be useful in callback methods.
/// The key property of the callback argument will in our case be the combinedKey.
/// To be interpreted, it needs to be split into domain and key with these parse methods.
/// </summary>
public static string ParseKey(string combinedKey)
{
return combinedKey.Substring(combinedKey.IndexOf(KeySeparator) + KeySeparator.Length);
}
/// <summary>
/// Create a combined key from given values.
/// The combined key is used when storing and retrieving from the inner MemoryCache instance.
/// Example: Product_76
/// </summary>
/// <param name="key">Key within specified domain</param>
/// <param name="domain">NULL will fallback to default domain</param>
private static string CombinedKey(object key, string domain)
{
return string.Format("{0}{1}{2}", string.IsNullOrEmpty(domain) ? DefaultDomain : domain, KeySeparator, key);
}
#endregion
}
关于c# - 支持区域的 MemoryCache?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9003656/
我读了MSDN documentation但并没有真正理解它。 我相信Set的行为是“替换现有的,或添加”(原子地)。 正确吗? 最佳答案 如果该键已存在值, Add 不会执行任何操作(返回 fals
我试图找到一种方法让 .net 4.0 MemoryCache.Default 实例使用不区分大小写的比较器。 那可能吗? var bob = new object(); MemoryCache.De
我试图弄清楚应该如何使用 MemoryCache 以避免出现内存不足异常。我来自 ASP.Net 背景,缓存管理它自己的内存使用,所以我希望 MemoryCache 会做同样的事情。正如我制作的波纹管
在 Controller 类中,我有 using Microsoft.Extensions.Caching.Memory; private IMemoryCache _cache; private r
Memcached API 有一个 Touch() 方法,它可以更新给定 key 的过期策略。如何使用 .Net ObjectCache 类最好地完成此任务? 我能看到的最好的办法是删除对象并重新添加
当使用 MemoryCache 时,可以设置 AbsoluteExpiration AbsoluteExpirationRelativeToNow 例子: cache.GetOrCreate(
根据 MSDN 文档 here : Do not create MemoryCache instances unless it is required. If you create cache ins
我需要添加缓存功能并找到了一个名为 MemoryCache 的新类。但是,我发现 MemoryCache 有点残缺(我需要区域功能)。除其他事项外,我需要添加类似 ClearAll(region) 的
在我的应用程序中,我使用 MemoryCache,但我不希望项目过期。因此,项目将使用默认策略插入到缓存中,而无需设置 AbsoulteExpiration 或 SlidingExpiration。
MemoryCache类公开了一个名为 .AddOrGetExisting 的方法这是一种线程安全的方法,如果存在则获取,如果不存在则添加。 如果缓存对象不存在,此方法返回 NULL。我想我理解它的值
MemoryCache 是否具有缓存固定数量项目的功能? 例如我们只对从数据库中缓存 2000 个项目感兴趣。在不断向缓存中添加项目的同时,如果超过指定的项目数,则可以删除最旧的项目。 如果不是,我们
我正在使用 .NET 4.0 MemoryCache应用程序中的类并试图限制最大缓存大小,但在我的测试中,缓存似乎并没有真正遵守限制。 我正在使用设置,according to MSDN ,应该限制缓
我将 MemoryCache 与 Sql 依赖项一起使用。我注意到当使用 MemoryCache.Set() 时,如果集合中的某个项目被覆盖,则会发生内存泄漏。考虑以下场景: key=A 的项被插入到
我一直在阅读有关从 .Net Framework 4.0 开始的新 MemoryCache 类的所有地方。根据我的阅读,您可以跨不同的 .Net 应用程序访问 MemoryCache。我正在尝试在 A
我收到这条消息: System.ObjectDisposedException: Cannot access a disposed object. A common cause of this err
应用程序需要加载数据并缓存一段时间。我希望如果应用程序的多个部分想要同时访问同一个缓存键,缓存应该足够智能,只加载一次数据并将该调用的结果返回给所有调用者。然而, MemoryCache 不是这样做的
MemoryCache 是一个线程安全类,根据 this文章。但我不明白它在特定情况下会如何表现。例如我有代码: static private MemoryCache _cache = MemoryC
我不明白在 .NET 4.0 的 System.Runtime.Caching.MemoryCache 中滑动过期应该如何工作。 根据文档,过期时间跨度是“在从缓存中逐出缓存条目之前必须访问缓存条目的
在 .NET 4 MemoryCache 中,有没有办法找到上次访问项目的时间?我确定它在内部被跟踪,因为 CacheItemPolicy 具有 SlidingExpiration 属性。但是我找不到
我正在使用 .NET 4.0 MemoryCache类,我想以线程安全的方式添加或替换缓存中的现有项,但我还想知道我是否替换了现有项或添加了新项。 据我所知,Set方法旨在原子地替换缓存中的项目(如果
我是一名优秀的程序员,十分优秀!