Inside Mendz.Library.IDGenerator

In Mendz.Library, one of the classes defined is the IDGenerator. The IDGenerator is a thread-safe generator of incremental integer values. It can be seeded to start from a seed number and increment from there. Simple right? Let's look at how it's done.

IDGenerator is a simple class with a constructor that can accept a seed value. The default seed is 1.

        public IDGenerator(int seed = 1) => Seed(seed);

An IDGenerator instance exposes a property named ID. It basically returns the current ID value. Note that the current ID value is declared volatile, which helps to make it safe for use in multi-threaded scenarios.

        private volatile int _id = 1;
        public int ID
        {
            get => _id;
        }

There are a couple of methods exposed by IDGenerator.

The Seed() method can be used to set the seed the ID to a new value. If the seed is less than 1, an ArgumentOutOfRangeException is thrown. If the seed value passed is less than the current ID value, the method does nothing. Observe that the operation performs a lock to prevent concurrent calls from clashing. This makes Seed() thread-safe.

        private object o = new object();
        public void Seed(int seed)
        {
            lock (o)
            {
                if (seed < 1)
                {
                    throw new ArgumentOutOfRangeException("seed", 
                        "The seed cannot be less than 1.");
                }
                if (_id < seed)
                {
                    _id = seed;
                }
            }
        }

The Generate() method generates a new ID value. It basically increments the ID property value using Interlocked.Increment(), which is the thread-safe way to do it.

        public int Generate()
        {
            lock (o)
            {
                return Interlocked.Increment(ref _id);
            }
        }

And that's about it! To use IDGenerator, just create an instance, get the initial ID and Generate() new IDs onwards. Easy as 1-2-3.

    IDGenerator idGenerator = new IDGenerator();
    Console.WriteLine(idGenerator.ID); // 1
    Console.WriteLine(idGenerator.Generate()); // 2
    Console.WriteLine(idGenerator.Generate()); // 3

Access the latest Mendz.Library codes at GitHub. The latest Mendz.Library binary can be downloaded from NuGet.

Comments