首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何清除MemoryCache?

如何清除MemoryCache?
EN

Stack Overflow用户
提问于 2010-11-15 18:05:05
回答 11查看 104.4K关注 0票数 110

我已经使用MemoryCache类创建了一个缓存。我向其中添加了一些项,但当我需要重新加载缓存时,我想首先清除它。完成此操作的最快方法是什么?我应该遍历所有的项目,一次删除一个项目,还是有更好的方法?

EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2010-11-15 18:12:46

Dispose现有的MemoryCache并创建一个新的MemoryCache对象。

票数 67
EN

Stack Overflow用户

发布于 2014-03-14 03:26:50

枚举的问题

MemoryCache.GetEnumerator() Remarks section警告:“检索MemoryCache实例的枚举器是一项资源密集型和阻塞操作。因此,不应在生产应用程序中使用枚举器。”

这里是的原因,在GetEnumerator()实现的伪代码中解释:

代码语言:javascript
复制
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查询的所有答案。

更好、更灵活的解决方案

这里有一种清除缓存的有效方法,它只需构建在现有的更改监视基础设施上。它还提供了清除整个缓存或仅清除命名子集的灵活性,并且不存在上面讨论的任何问题。

代码语言:javascript
复制
// 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;
        }
    }
}
票数 58
EN

Stack Overflow用户

发布于 2012-02-29 22:00:12

来自http://connect.microsoft.com/VisualStudio/feedback/details/723620/memorycache-class-needs-a-clear-method

解决方法是:

代码语言:javascript
复制
List<string> cacheKeys = MemoryCache.Default.Select(kvp => kvp.Key).ToList();
foreach (string cacheKey in cacheKeys)
{
    MemoryCache.Default.Remove(cacheKey);
}
票数 36
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4183270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档