我使用MemoryCache类创建了一个缓存。我添加了一些项目,但是当我需要重新加载缓存时,我想首先清除它。最快的方法是什么?我应该遍历所有项目并一次删除一个项目还是有更好的方法?
答案 0 :(得分:53)
Dispose
现有的MemoryCache并创建一个新的MemoryCache对象。
答案 1 :(得分:51)
MemoryCache.GetEnumerator() Remarks section警告:"检索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
由于实现将缓存分割为多个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;
}
}
}
答案 2 :(得分:31)
解决方法是:
List<string> cacheKeys = MemoryCache.Default.Select(kvp => kvp.Key).ToList();
foreach (string cacheKey in cacheKeys)
{
MemoryCache.Default.Remove(cacheKey);
}
答案 3 :(得分:20)
var cacheItems = cache.ToList();
foreach (KeyValuePair<String, Object> a in cacheItems)
{
cache.Remove(a.Key);
}
答案 4 :(得分:9)
如果表演不是问题,那么这个漂亮的单行将会起到作用:
cache.ToList().ForEach(a => cache.Remove(a.Key));
答案 5 :(得分:7)
答案 6 :(得分:3)
您也可以这样做:
Dim _Qry = (From n In CacheObject.AsParallel()
Select n).ToList()
For Each i In _Qry
CacheObject.Remove(i.Key)
Next
答案 7 :(得分:2)
在此基础上,编写了一个稍微更有效,平行的方法:
public void ClearAll()
{
var allKeys = _cache.Select(o => o.Key);
Parallel.ForEach(allKeys, key => _cache.Remove(key));
}
答案 8 :(得分:1)
我只对清除缓存感兴趣,并在使用c#GlobalCachingProvider时发现它是一个选项
var cache = GlobalCachingProvider.Instance.GetAllItems();
if (dbOperation.SuccessLoadingAllCacheToDB(cache))
{
cache.Clear();
}
答案 9 :(得分:0)
magritte答案的一点改进版本。
var cacheKeys = MemoryCache.Default.Where(kvp.Value is MyType).Select(kvp => kvp.Key).ToList();
foreach (string cacheKey in cacheKeys)
{
MemoryCache.Default.Remove(cacheKey);
}
答案 10 :(得分:0)
您可以处理MemoryCache.Default缓存,然后将私有字段单例重置为null,以使其重新创建MemoryCache.Default。
var field = typeof(MemoryCache).GetField("s_defaultCache",
BindingFlags.Static |
BindingFlags.NonPublic);
field.SetValue(null, null);