Skip to content
Extension methods for System.Runtime.Caching.ObjectCache / MemoryCache with locking mechanism.
C# Batchfile
Branch: master
Clone or download
Latest commit 1af1ebe May 23, 2017
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
NuGet
SimpleCache.Tests Added Async tests May 23, 2017
SimpleCache
.gitattributes
.gitignore Added NuGet push (with SymbolSource) Nov 21, 2014
LICENSE
README.md
SimpleCache.sln

README.md

SimpleCache

  • Allows you to check if some value exists in cache and if not, acquire the value and put it in cache, using 1 method call.
  • Takes care of locking while the value is being acquired when it does not yet exist in cache.
  • Generates cachekeys including the type name being cached so you can use the same key (ie FindAll) for different types.

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();
});

Project page

http://simplecache.xpericode.com/

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

You can’t perform that action at this time.