I need to generate a unique sequence number from multiple threads. I created the simple class below and it seems to work, but I'm not certain if I can rely on the sequence number being unique.
In addition, I need to be able to have the number go back to 0 if it exceeds 999999. I don't expect it to roll over for a very long time as the method will likely be called less than 100 times per day. I know that the system will be shut down periodically for maintenance before it has a chance to reach 999999.
The GetSequenceNumber
method will be called from an xslt transformation in a BizTalk map and the method could be called more than once at the same time (within the same BizTalk host instance).
On my dev system, it seems to work correctly and generates different values even if BizTalk is calling the method more than once at the same time. The dev system only has a single BizTalk host instance running.
On the production system, however, there are two servers. Am I right in thinking that this method cannot guarantee uniqueness across servers since they are running in different App Domains?
I can't use a guid because the sequence number is limited to 16 characters.
public class HelperMethods
{
private static int sequenceNumber = 0;
public string GetSequenceNumber()
{
string result = null;
int seqNo = Interlocked.Increment(ref sequenceNumber);
result = string.Format("{0:MMddHHmmss}{1:000000}", DateTime.Now, seqNo);
return result;
}
}
I thought that I might be able to use the servers computer name and prepend some arbitrary character so that even if the sequence number generated on one server was the same as the other, it would still be different, but I'm not sure how unique it would be. Something like this:
string seqNumber = (MachineName == "Blah" ? "A" : "B") + GetSequenceNumber();
Does anyone have any suggestions as to how I can create a unique sequence number? It doesn't have to be perfectly unique, I just need collisions to be very unlikely. Also, how can I reset the number back to 0 if it reaches 1000000 in a thread safe way?