You can create a singleton class for it which contains a private counter and a method to retrieve the counter. However, the retrieve method has a lock so it get executed one thread at a time.
Since it's a singleton class, it will instantiate once when the program gets run and you can initialize your counter from the maximum value available for id in your database and after that it would get increased without duplication or interruption.
Here's some sample code in console:
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
var counter = SingletonCounter.GetInstance();
ThreadStart start = new ThreadStart(delegate
{
var id = counter.GetId();
});
new Thread(start).Start();
}
Console.ReadLine();
}
}
public class SingletonCounter
{
private static SingletonCounter _instance;
private readonly object _object = new object();
private long _id;
private SingletonCounter()
{
_id = 0;//you can initiate with maximum id available in database when run the application
}
public static SingletonCounter GetInstance()
{
return _instance ??= new SingletonCounter();
}
public long GetId()
{
lock (_object)
{
Console.WriteLine(_id);
return _id++;
}
}
}