I have some code in which I use SemaphoreSlim
:
if (!string.IsNullOrEmpty(UserSettings.Token) && !isWithoutRefresh)
{
if (UserSettings.Expires < ConvertToTimestamp(DateTime.UtcNow.AddMinutes(2)))
{
await _locker.LockAsync(async () =>
{
if (UserSettings.Expires < ConvertToTimestamp(DateTime.UtcNow.AddMinutes(2)))
{
if (Role.Guest.Equals(UserSettings.Role)
&& !string.IsNullOrEmpty(UserSettings.Email))
{
//TODO: initialize guest session
}
else
{
await RefreshToken(httpClient);
await AlertService.ShowAsync("Odswiezony");
}
}
});
}
}
This is the code for my _locker
:
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
public async Task LockAsync(Func<Task> worker)
{
await _semaphore.WaitAsync();
try
{
await worker();
}
finally
{
_semaphore.Release();
}
}
My question is that what I can do to release all threads async after one of my threads inside the locker made some action? Because in this situation, every thread will be made synchronously. My desired solution is to have logic when I need to Refresh the token and more than 1 thread can make this action allow only the first of them to do this, and make rest of them asynchronous.