Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock an object that creates ID

Tags:

c#

locking

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;
    }
}
like image 878
BossRoss Avatar asked Oct 23 '13 12:10

BossRoss


2 Answers

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.

like image 110
Mike Perrenoud Avatar answered Oct 13 '22 18:10

Mike Perrenoud


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.

like image 3
Szymon Avatar answered Oct 13 '22 18:10

Szymon