I need to implement some thread consequent logic in Azure web instances. I have some code like this:
lock (_bookingLock)
{
// Check for a free time
bool isTimeFree = _scheduleService.IsTimeFree(dateTimeGuidId);
//* race condition here
if (isTimeFree)
{
// Make a booking. So this time is busy
newBookingId = _paymentService.CreateBooking(dateTimeGuidId).ToString();
}
}
But I can't use lock
in a multi instance environment and I can't omit lock because there is a race condition at *
. What is the best approach here?
I decided to use blob leases. I upgraded smarx's code to use Azure Storage client version 2 or 3 and wrote one addtitional method. Here is full code:
Here is how to use this (don't forget about setup config for blob connection string and catalog name):