Created
March 6, 2015 20:32
-
-
Save owen2/b463a773fe786d030963 to your computer and use it in GitHub Desktop.
A cache for your async tasks so that you can await the same result multiple times
This file contains 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
using System; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
namespace DataStructures | |
{ | |
public class AsyncGeneratorCache<TKey, TValue> | |
{ | |
private Func<TKey, Task<TValue>> _generate; | |
private Dictionary<TKey, Task<TValue>> _promises = new Dictionary<TKey, Task<TValue>>(); | |
public AsyncGeneratorCache(Func<TKey, Task<TValue>> generatorFunction) | |
{ | |
_generate = generatorFunction; | |
} | |
public async Task<TValue> Get(TKey key) | |
{ | |
if (!_promises.ContainsKey(key)) | |
_promises[key] = _generate(key); | |
return await _promises[key]; | |
} | |
public void Set(TKey key, TValue value) | |
{ | |
_promises[key] = Task.Run(() => value); | |
} | |
public void Remove(TKey key) | |
{ | |
_promises.Remove(key); | |
} | |
public IEnumerable<TKey> Keys { get { return _promises.Keys; } } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment