Last active
October 25, 2018 13:39
-
-
Save unsafePtr/56f2821a8dc8d1cc87d7af1620a43076 to your computer and use it in GitHub Desktop.
Example of cache decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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