I am looking for an elegant way of caching the results of my asynchronous operations.
I first had a synchronous method like this:
public String GetSt
Another easy way to do this is to extend Lazy to be AsyncLazy, like so:
public class AsyncLazy : Lazy>
{
public AsyncLazy(Func> taskFactory, LazyThreadSafetyMode mode) :
base(() => Task.Factory.StartNew(() => taskFactory()).Unwrap(), mode)
{ }
public TaskAwaiter GetAwaiter() { return Value.GetAwaiter(); }
}
Then you can do this:
private readonly ConcurrentDictionary> _cache
= new ConcurrentDictionary>();
public async Task GetStuffAsync(string url)
{
return await _cache.GetOrAdd(url,
new AsyncLazy(
() => GetStuffInternalAsync(url),
LazyThreadSafetyMode.ExecutionAndPublication));
}