Skip to content

Add .Clear() method to MemoryCache #45593

Closed

Description

Background and Motivation

MemoryCache gives the possibility to add and remove a single cache entry, but it does not allow for clearing the entire cache at once.

Many (more than twenty by looking at the number of reactions) of our customers have expressed the need of this API in #36547.

So far most of them was forced to use ugly workarounds like using reflection or trimming the cache to a very small size.

Proposed API

namespace Microsoft.Extensions.Caching.Memory
{
    public class MemoryCache
    {
+        public void Clear();
    }
    
    public interface IMemoryCache
    {
+        void Clear();
    }
}

Usage Examples

var cache = new MemoryCache(new MemoryCacheOptions());

cache.Set("key1", "value1");
cache.Set("key2", "value2");

cache.Clear();

Risks

Adding a new method to the IMemoryCache interface is going to break users who implemented their own cache. This should be rare.

According to my understanding, adding it with a default empty implementation would require changing the target framework from .NET Standard 2.0 to .NET 6.0?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions