Consider a following pseudo code:
private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
private static Token CachedToken = new Token();
public async Task DoWorkAsync()
{
var token = CachedToken;
if (!token.IsInvalid) { //new Token() is invalid
var response = await _apiClient.MakeRequest(token);
if (response.StatusCode != HttpStatusCode.Unauthorized) {
return response;
}
}
await _semaphore.WaitAsync();
try {
if (CachedToken.AccessToken == token.AccessToken) {
CachedToken = await GetFreshToken();
}
token = CachedToken;
}
finally {
_semaphore.Release();
}
return await _apiClient.MakeRequest(token);
}
So my question is how to unlock all threads waiting for semaphore as soon as first thread has updated the cache and got released?