Ret*_*der 91 c# memory caching .net-4.0 memorycache
我使用MemoryCache类创建了一个缓存.我添加了一些项目,但是当我需要重新加载缓存时,我想首先清除它.最快的方法是什么?我应该遍历所有项目并一次删除一个项目还是有更好的方法?
GvS*_*GvS 57
Dispose 现有的MemoryCache并创建一个新的MemoryCache对象.
Tho*_*ham 54
所述MemoryCache.GetEnumerator()备注部警告:"检索了的MemoryCache实例的枚举是资源密集型的,阻塞操作因此,枚举不应该在生产应用中使用".
这就是为什么,在GetEnumerator()实现的伪代码中解释:
Create a new Dictionary object (let's call it AllCache)
For Each per-processor segment in the cache (one Dictionary object per processor)
{
Lock the segment/Dictionary (using lock construct)
Iterate through the segment/Dictionary and add each name/value pair one-by-one
to the AllCache Dictionary (using references to the original MemoryCacheKey
and MemoryCacheEntry objects)
}
Create and return an enumerator on the AllCache Dictionary
Run Code Online (Sandbox Code Playgroud)
由于实现将缓存分割为多个Dictionary对象,因此它必须将所有内容组合到一个集合中以便返回枚举器.每次调用GetEnumerator都会执行上面详述的完整复制过程.新创建的Dictionary包含对原始内部键和值对象的引用,因此不会复制实际的缓存数据值.
文档中的警告是正确的.避免使用GetEnumerator() - 包括上面使用LINQ查询的所有答案.
这是一种清除缓存的有效方法,只需在现有的变更监控基础架构上构建.它还提供了清除整个缓存或仅清除命名子集的灵活性,并且没有上面讨论的问题.
// By Thomas F. Abraham (http://www.tfabraham.com)
namespace CacheTest
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Caching;
public class SignaledChangeEventArgs : EventArgs
{
public string Name { get; private set; }
public SignaledChangeEventArgs(string name = null) { this.Name = name; }
}
/// <summary>
/// Cache change monitor that allows an app to fire a change notification
/// to all associated cache items.
/// </summary>
public class SignaledChangeMonitor : ChangeMonitor
{
// Shared across all SignaledChangeMonitors in the AppDomain
private static event EventHandler<SignaledChangeEventArgs> Signaled;
private string _name;
private string _uniqueId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
public override string UniqueId
{
get { return _uniqueId; }
}
public SignaledChangeMonitor(string name = null)
{
_name = name;
// Register instance with the shared event
SignaledChangeMonitor.Signaled += OnSignalRaised;
base.InitializationComplete();
}
public static void Signal(string name = null)
{
if (Signaled != null)
{
// Raise shared event to notify all subscribers
Signaled(null, new SignaledChangeEventArgs(name));
}
}
protected override void Dispose(bool disposing)
{
SignaledChangeMonitor.Signaled -= OnSignalRaised;
}
private void OnSignalRaised(object sender, SignaledChangeEventArgs e)
{
if (string.IsNullOrWhiteSpace(e.Name) || string.Compare(e.Name, _name, true) == 0)
{
Debug.WriteLine(
_uniqueId + " notifying cache of change.", "SignaledChangeMonitor");
// Cache objects are obligated to remove entry upon change notification.
base.OnChanged(null);
}
}
}
public static class CacheTester
{
public static void TestCache()
{
MemoryCache cache = MemoryCache.Default;
// Add data to cache
for (int idx = 0; idx < 50; idx++)
{
cache.Add("Key" + idx.ToString(), "Value" + idx.ToString(), GetPolicy(idx));
}
// Flush cached items associated with "NamedData" change monitors
SignaledChangeMonitor.Signal("NamedData");
// Flush all cached items
SignaledChangeMonitor.Signal();
}
private static CacheItemPolicy GetPolicy(int idx)
{
string name = (idx % 2 == 0) ? null : "NamedData";
CacheItemPolicy cip = new CacheItemPolicy();
cip.AbsoluteExpiration = System.DateTimeOffset.UtcNow.AddHours(1);
cip.ChangeMonitors.Add(new SignaledChangeMonitor(name));
return cip;
}
}
}
Run Code Online (Sandbox Code Playgroud)
mag*_*tte 33
解决方法是:
List<string> cacheKeys = MemoryCache.Default.Select(kvp => kvp.Key).ToList();
foreach (string cacheKey in cacheKeys)
{
MemoryCache.Default.Remove(cacheKey);
}
Run Code Online (Sandbox Code Playgroud)
Rog*_*Far 21
var cacheItems = cache.ToList();
foreach (KeyValuePair<String, Object> a in cacheItems)
{
cache.Remove(a.Key);
}
Run Code Online (Sandbox Code Playgroud)
如果性能不是问题,那么这个漂亮的单行将会起到作用:
cache.ToList().ForEach(a => cache.Remove(a.Key));
Run Code Online (Sandbox Code Playgroud)
似乎有一种修剪方法.
所以要清除你刚刚做的所有内容
cache.Trim(100)
Run Code Online (Sandbox Code Playgroud)
编辑: 经过挖掘更多,似乎调查修剪是不值得的时间
如何清除System.Runtime.Caching.MemoryCache
| 归档时间: |
|
| 查看次数: |
76446 次 |
| 最近记录: |