I have a table that keeps track of a global serial number shared between several tables. This is not the PK or unique id for each table. It is like a case identifier. Every time users create a new entity we need to give them a unique serial number from this row. My worries is what happens if 2 users hit the method for incrementing this counter at the exact same time. Would this solution be enough?
Also this code would be run from 2 servers using the same database.
public string GetIdentifier()
{
int retries = 0;
bool success = false;
string newId;
do
{
try
{
var tracker = Trackers.Find(1);
newId = tracker.Increment();
SaveChanges();
success = true;
}
catch (DbUpdateConcurrencyException)
{
Thread.Sleep(500);
if (++retries == 5)
throw;
}
catch (Exception)
{
//do some logging
throw;
}
} while (!success);
return newId;
}