Created
June 16, 2023 17:00
-
-
Save cheoalfredo/c742e3dfccfb7469e32a13b9e6ce0407 to your computer and use it in GitHub Desktop.
Acquire a lock with retries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[HttpGet(Name = "GetWeatherForecast")] | |
public async Task<IEnumerable<WeatherForecast>> Get() | |
{ | |
await using var _lock = await _LockFactory.CreateLockAsync( | |
typeof(WeatherForecast).Name, | |
TimeSpan.FromSeconds(10), // need a lock for 10 seconds | |
TimeSpan.FromSeconds(3), // wait 3 seconds to attempt and acquire a lock | |
TimeSpan.FromSeconds(1) // retry every 1 second | |
);| | |
if (_lock.IsAcquired) | |
{ | |
await Task.Delay(TimeSpan.FromSeconds(10)); | |
return Enumerable.Range(1, 5).Select(index => new WeatherForecast | |
{ | |
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), | |
TemperatureC = Random.Shared.Next(-20, 55), | |
Summary = Summaries[Random.Shared.Next(Summaries.Length)] | |
}) | |
.ToArray(); | |
} | |
throw new InvalidOperationException("Resource is locked right now. Try again later!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment