In my application I have a BackgroundService which also includes the following method:
- GetNumberAsync() gets the "oldest" record from database and updates the properties of the record.
This method is called from API controller async method like:
[HttpGet]
[Route("GetNumber")]
public async Task<ActionResult<string>> GetNumber()
{
return Ok(await _numberService.GetNumberAsync());
}
I'm afraid that if two or more calls of GetNumberAsync() at the same time occurs then some of them may get the same record. How to avoid it, because every call should return a unique record?
Method code:
internal async Task<string> GetNumberAsync()
{
var num = await _smsDbContext.ZadarmaPhoneNumbers
.OrderBy(x => x.LockedTime)
.FirstOrDefaultAsync();
if(num != null)
{
num.LockedTime = DateTime.Now;
num.SmsCode = "";
_smsDbContext.ZadarmaPhoneNumbers.Update(num);
await _smsDbContext.SaveChangesAsync();
return num.Number;
}
return "";
}
Thanks.