How to generate a sequential unique id in a thread-safe way

Viewed 2013

i have called multiple threads which generates a number but i wanted to generate a unique no with all threads,( suppose one thread generates a no ie ABC1 but second thread must generate ABC2 and so on)

2 Answers

You could use Interlocked.Increment, which will complete a thread safe increment on the counter.

public class Person
{
    private static int _counter;

    public string GetNewId()
    {
        int id = Interlocked.Increment(ref _counter);
        return $"ABC{id}";
    }
}

If you just want a thread safe way to generate unique numbers, then you can do something like this:

private static object _lock = new object();
private static int mIdx = 0;
public static string GenerateNumber()
{
     lock (_lock)
     {
          return $"ABC{mIdx++}";
     }
}
Related