View on GitHub

SimpleCache

Extension methods for System.Runtime.Caching.ObjectCache / MemoryCache with locking mechanism.

Download this project as a .zip file Download this project as a tar.gz file

SimpleCache

Build status NuGet version

Installation

The SimpleCache package is available at NuGet. To install SimpleCache, run the following command in the Package Manager Console:

Install-Package XperiCode.SimpleCache

Examples

Get a value from cache and if it does not exist in cache yet, acquire it and put it in cache:

var person = MemoryCache.Default.Get("Find", () => _personRepository.Find());

Same as above but the value will stay in the cache for only 15 minutes:

var person = MemoryCache.Default.Get("Find", TimeSpan.FromMinutes(15), () => 
{
    return _personRepository.Find();
});

There are methods available to invalidate cache at an absolute expirationdate or when a certain file has changed as well. For all these methods there are async versions available in case the acquire method is async:

var person = await MemoryCache.Default.GetAsync("Find", () => 
{
    return _personRepository.FindAsync();
});

If the acquire method takes a long time to finish, the extension methods take care of locking (even the async versions) so the acquire method will not be called multiple times after the value is acquired. So if 10 visitors would visit a webpage with the following code at the same time, the SomeLongRunningMethod method and _personRepository.Find() call will only be called once:

var person = MemoryCache.Default.Get("Find", () =>
{
    SomeLongRunningMethod();
    return _personRepository.Find();
});

Collaboration

Please report issues if you find any. Pull requests are welcome!