Skip to content

Instantly share code, notes, and snippets.

@rippo
Last active April 9, 2019 07:01
Show Gist options
  • Save rippo/e6347c06cd232a9aac422e5878ef78b0 to your computer and use it in GitHub Desktop.
Save rippo/e6347c06cd232a9aac422e5878ef78b0 to your computer and use it in GitHub Desktop.

The caching logic is slightly flawed. During the time the http request is in progress, foo is left unpopulated, and if another method calls GetFooDataAsync() during this time, the http request will be repeated.

Ideally the cache should populate only once.

To ensure one and only one invocation of the task, cache the task itself, not the result, and simply await it whenever you want to get the result. A second or third await won't invoke the method again, it'll simply access the existing result.

Source https://stackoverflow.com/questions/55585644/async-await-with-method-calling-external-resource-or-returning-local-string#55585821

private static Task<string> foo = null;
private static async Task<string> GetFooDataAsync()
{
async Task<string> GetFooDataInternal()
{
var response = await myHttpClient.GetFooAsync();
return response.data;
}
if (foo == null) foo = GetFooDataInternal();
return await foo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment