Skip to content

Instantly share code, notes, and snippets.

@cheoalfredo
Created June 16, 2023 17:00
Show Gist options
  • Save cheoalfredo/c742e3dfccfb7469e32a13b9e6ce0407 to your computer and use it in GitHub Desktop.
Save cheoalfredo/c742e3dfccfb7469e32a13b9e6ce0407 to your computer and use it in GitHub Desktop.
Acquire a lock with retries
[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