Multiple calls to async function with cache in C#
async-await, asynchronous, c#, task-parallel-library
Solution
Use `Lazy`.
//the lazy can be changed to an instance variable, if that's appropriate in context.
private static Lazy<Task<Customer>> lazy =
new Lazy<Task<Customer>>(() => GetFromWebService());
public Task<Customer> GetCustomer(){
return lazy.Value;
}
This will ensure that exactly one `Task` is ever created, and that the web service call isn't made until at least one request is made. Any future requests will then return the same `Task` (whether its in progress or complete) which can be awaited to get the value.
Problem
I have a function that can be called from many UI elements at the same time: In Psudeo code ``` public async Task<Customer> GetCustomer(){ if(IsInCache) return FromCache; cache = await GetFromWebService(); return cache; } ``` If 10 UI element all call at the same time, how do I make sure GetFromWebService() is called just once, it is very expensive.