Threadsafe incrementing value

Is the following threadsafe, and if not how should I achieve the assignment of a guaranteed unique key. I like many others have skipped all over MSDN almost but not quite getting the answer I want. (If only there were more examples for us beginners)

class FamilyMember

{

    private static object LockObject = new object();

    private static int _FamilyKeyGenerator = 0;

    private int FamilyKeyGenerator { get { lock (_LockObject) { return _FamilyKeyGenerator++; } } }

    private int _FamilyKey; public int FamilyKey { get { return _FamilyKey; } }

    public class  FamilyMember(bool isHeadOfFamily)

    {

        if(isHeadOfFamily) _FamilyKey = FamilyKeyGenerator;

    }

}

 

 

 

 



Answer this question

Threadsafe incrementing value

  • Peter Gloor

    Yeah, that's threadsafe.


  • Mr. Emu

    The Interlocked.Decrement method is a simpler way of doing this.

    Of course, your key will only be unique within a particular process. If I run two instances of your application I will get overlapping keys. Generally keys needs to persisted to shared storage, e.g., a database. Apologies if you already know this.


  • Threadsafe incrementing value