Skip to content

Instantly share code, notes, and snippets.

@unsafePtr
Last active October 25, 2018 13:39
Show Gist options
  • Select an option

  • Save unsafePtr/56f2821a8dc8d1cc87d7af1620a43076 to your computer and use it in GitHub Desktop.

Select an option

Save unsafePtr/56f2821a8dc8d1cc87d7af1620a43076 to your computer and use it in GitHub Desktop.
Example of cache decorator
// Used as an interceptor to provide cache mechanism.
// ISomeService can be any other service and this is just an example for you own class cache.
// Should be used as singleton to get benefit from it.
public class CacheDecorator : ISomeService
{
private static ConcurrentDictionary<string, Task<string>> Cache { get; } = new ConcurrentDictionary<string, Task<string>>();
private ISomeService Implementation { get; }
public CacheDecorator(ISomeService implementation)
{
Implementation = implementation;
}
public Task<string> GetAsync(string id)
{
string key = id;
if (Cache.TryGetValue(key, out var item))
{
return item;
}
else
{
return Implementation.GetAsync(key).ContinueWith(task =>
{
Cache.TryAdd(key, task);
return task.Result; // we don't block with task.Result because task is already finished
});
}
}
}
public interface ISomeService
{
Task<string> GetAsync(string id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment