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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With