Would the following method ensure that only one thread can read an ID at a time? I have a parallel process which uses the following method and I need it to return unique IDs. Unfortunately I cannot change the way the ID is structured.
private static int Seq = 0;
private static long dtDiff = 0;
private static object thisLock = new object();
private static object BuildClientID(string Code)
{
lock (thisLock)
{
object sReturn = "";
Seq++;
dtDiff++;
if (Seq == 1000)
{
Seq = 0;
dtDiff = DateAndTime.DateDiff(DateInterval.Second, DateTime.Parse("1970-01-01"), DateTime.Now);
}
sReturn = dtDiff.ToString() + Code + Seq.ToString("000");
return sReturn;
}
}
I don't see any reason it wouldn't. Both the lock object and the method are static
. The only thing you need to determine is, do you need a more sophisticated form of locking like a Mutex
, SpinLock
, ReaderWriterLock
, or Semaphore
.
You'll need to study those, and here is a good link to get started.
Yes, it will work fine as both threads will use the same static object as the lock object and will have to wait for each other.
edit
Based on Dan's comments: consider making Seq
and dtDiff
properties and put access to them inside the same lock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With