Simon H
Simon H

Reputation: 565

C# async subsequent calls return existing task

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

Answers (1)

Stephen Cleary
Stephen Cleary

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:

  • Can InterfaceAsync be called from multiple threads? If so, then _task needs to be protected.
  • Is this code loading a resource only one time? If so, then consider using AsyncLazy<T> instead of Task<T>.
  • Should this code re-load the resource on the next call if the old call has already completed? If so, then the cached Task<T>/AsyncLazy<T> needs to be replaced when the call completes.
  • Is caching errors OK, or should the next call always retry any previous errors?

Upvotes: 2

Related Questions