Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 344
Sandeep More Avatar asked Mar 06 '23 03:03

Sandeep More


1 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}";
    }
}
like image 165
Evan Trimboli Avatar answered Mar 07 '23 16:03

Evan Trimboli