I am trying to generate unique integer
Ids that can be used from multiple threads.
public partial class Form1 : Form
{
private static int sharedInteger;
...
private static int ModifySharedIntegerSingleTime()
{
int unique = Interlocked.Increment(ref sharedInteger);
return unique;
}
SimulateBackTestRow1()
{
while (true)
{
int num = ModifySharedIntegerSingleTime();
}
}
SimulateBackTestRow2()
{
while (true)
{
int num = ModifySharedIntegerSingleTime();
}
}
Task modifyTaskOne = Task.Run(() => SimulateBackTestRow1());
Task modifyTaskTwo = Task.Run(() => SimulateBackTestRow2());
However, when code that takes a unique number that has not been used before gets passed a number that was acquired by ModifySharedIntegerSingleTime
, I am getting collisions with numbers that are not unique.
What is the correct way to get unique int Ids in a thread-safe
way?