Reputation: 68810
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.
Upvotes: 4
Views: 846
Reputation: 457057
If your cache is in-memory, you can cache the task rather than the result:
private Task<Customer> _cache;
public Task<Customer> GetCustomerAsync()
{
if (_cache != null)
return _cache;
_cache = GetFromWebServiceAsync();
return _cache;
}
Upvotes: 1
Reputation: 203830
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.
Upvotes: 12