Reputation: 565
I have web application which calls an external API for data.
If a user triggers this external call, and the call is already in effect, I don't want a second request to trigger a new call, but instead wait for the result of the first call (the result of the call will be the same for both requests).
How can I achieve this in c# using async/ await?
Upvotes: 0
Views: 189
Reputation: 456322
subsequent calls return existing task
Sure, you can do that just by keeping the Task<T>
object and then returning it.
Something like:
private async Task<T> ImplementationAsync();
private Task<T> _task;
public Task<T> InterfaceAsync()
{
if (_task == null)
_task = ImplementationAsync();
return _task;
}
This is an extremely simple example. Real-world code should consider:
InterfaceAsync
be called from multiple threads? If so, then _task
needs to be protected.AsyncLazy<T>
instead of Task<T>
.Task<T>
/AsyncLazy<T>
needs to be replaced when the call completes.Upvotes: 2