Skip to content

Instantly share code, notes, and snippets.

@owen2
Created March 6, 2015 20:32
Show Gist options
  • Save owen2/b463a773fe786d030963 to your computer and use it in GitHub Desktop.
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
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