English 中文(简体)
我如何明确一个制度。 午餐
原标题:How do I clear a System.Runtime.Caching.MemoryCache

我使用<代码>System.Runtime.Caching.MemoryCache持有永远不会到期的项目。 然而,有时我需要清除整个海滩。 我如何这样做?

我询问了一个类似的问题here。 关于我是否可以列举这些藏匿点,但这是一个坏的想法,因为在列举时需要加以精简。

I ve Trial using .Trim(100) but that don t work at all.

我试图通过Linq获得一份所有关键人物的名单,但随后我回头来,因为逐个逐个逐个项目很容易导致种族状况。

我想储存所有钥匙,然后发行<代码>。 每人搬走(钥匙),但也有暗含的种族条件,因此,我需要锁定钥匙清单,而且事情再次出现。

我当时认为,我应当能够打电话到<代码>.Dispose(),以了解整个切身情况,但我不敢肯定,由于执行方式,这才是最佳办法。

使用<代码>Change Monitors对我的设计来说不是一个选择,对于这种三维要求来说,是毫无道理的。

So, how do I completely clear the cache?

最佳回答

如果你想再利用,你就不应要求处置记忆库中的缺陷成员:

The state of the cache is set to indicate that the cache is disposed. Any attempt to call public caching methods that change the state of the cache, such as methods that add, remove, or retrieve cache entries, might cause unexpected behavior. For example, if you call the Set method after the cache is disposed, a no-op error occurs. If you attempt to retrieve items from the cache, the Get method will always return Nothing. http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.dispose.aspx

About the Trim, it s supposed to work:

The Trim property first removes entries that have exceeded either an absolute or sliding expiration. Any callbacks that are registered for items that are removed will be passed a removed reason of Expired.

If removing expired entries is insufficient to reach the specified trim percentage, additional entries will be removed from the cache based on a least-recently used (LRU) algorithm until the requested trim percentage is reached.

但另外2个用户报告说,它在同一个网页上做了大量的工作,因此我猜测你与Remove(

Update However I see no mention of it being singleton or otherwise unsafe to have multiple instances so you should be able to overwrite your reference.

但是,如果你需要从Default案中解放记忆,你就必须用人工清除,或通过处置永久销毁(使其无法使用)。

根据你的问题,你可以让自己的单一吨位的阶级回到你可以自行处置的记忆。 具有切身性质:-

问题回答

我首先要为此而努力。 记忆中心。 三角是最佳尝试,因此,如果藏有100件物品,你称之为Trim(100)将消除使用最少的产品。

特里姆收回被拆除的物品,大多数人期望清除所有物品。

This code removes all items from MemoryCache for me in my xUnit tests with MemoryCache.Default. MemoryCache.Default is the default Region.

foreach (var element in MemoryCache.Default)
{
    MemoryCache.Default.Remove(element.Key);
}

Here s is what I had made for something I was working on...

public void Flush()
{
    List<string> cacheKeys = MemoryCache.Default.Select(kvp => kvp.Key).ToList();
    foreach (string cacheKey in cacheKeys)
    {
        MemoryCache.Default.Remove(cacheKey);
    }
}

I know this is an old question but the best option I ve come across is to

Dispose the existing MemoryCache and create a new MemoryCache object. https://stackoverflow.com/a/4183319/880642

The answer doesn t really provide the code to do this in a thread safe way. But this can be achieved using Interlocked.Exchange

var oldCache = Interlocked.Exchange(ref _existingCache, new MemoryCache("newCacheName"));
oldCache.Dispose();

This will swap the existing cache with a new one and allow you to safely call Dispose on the original cache. This avoids needing to enumerate the items in the cache and race conditions caused by disposing a cache while it is in use.


<><>Edit>/strong>

这里,我如何在实际中利用这个数据来核算国际交易日志。

public class CustomCacheProvider : ICustomCacheProvider
{
    private IMemoryCache _internalCache;
    private readonly ICacheFactory _cacheFactory;

    public CustomCacheProvider (ICacheFactory cacheFactory)
    {
        _cacheFactory = cacheFactory;
        _internalCache = _cacheFactory.CreateInstance();
    }
    public void Set(string key, object item, MemoryCacheEntryOptions policy)
    {
        _internalCache.Set(key, item, policy);
    }

    public object Get(string key)
    {
        return _internalCache.Get(key);
    }
   // other methods ignored for breviy 

    public void Dispose()
    {
        _internalCache?.Dispose();
    }

    public void EmptyCache()
    {
        var oldCache = Interlocked.Exchange(ref _internalCache, _cacheFactory.CreateInstance());
        oldCache.Dispose();
    }
}

钥匙是利用另一个单一州控制内部海滩的进入,后者有能力利用工厂(或如果你愿意,则采用人工方式)制造新的海滩。

The details in @stefan s answer detail the principle; here s how I d do it.

在重新计算时,应尽量缩短接触海滩的机会,以避免客户守则在处置后、但在重整之前进入海滩的种族条件。

为了避免这种同步化,在您的适应班(总结记忆):

public void clearCache() {
  var oldCache = TheCache;
  TheCache = new MemoryCache("NewCacheName", ...);
  oldCache.Dispose();
  GC.Collect();
}

这样,TheCache就永远处于无处置状态,不需要同步化。

I ran into this problem too. .Dispose() did something quite different than what I expected.

相反,我给我的控制阶层增加了一个静态的领域。 我没有使用默认的藏匿处,来绕过这一行为,而是设立了一个私人机构(如果你要说的话)。 因此,我的执行看起来是这样:

public class MyController : Controller
{

    static MemoryCache s_cache = new MemoryCache("myCache");

    public ActionResult Index()
    {

        if (conditionThatInvalidatesCache)
        {
            s_cache = new MemoryCache("myCache");
        }

        String s = s_cache["key"] as String;

        if (s == null)
        {
            //do work
            //add to s_cache["key"]
        }

        //do whatever next
    }
}

Check out this post, and specifically, the answer that Thomas F. Abraham posted. It has a solution that enables you to clear the entire cache or a named subset.

这里的关键是:

// Cache objects are obligated to remove entry upon change notification.
base.OnChanged(null);

我已亲自执行,一切似乎都行不通。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签