I have code like this:
static volatile int i = 0;
static void Foo() {
int myInt = i++;
// now use myInt
}
I need to have each value of myInt unique and consecutive. For example, if there will be running 5 such threads, they should have myInt values 0, 1, 2, 3, 4 (order isn’t important).
So, I want no know if this way is thread-safe or not, and what’s the best way to achieve what I need?
For thread safety use Interlocked.Increment():
[…and there is no reason to mark as volatile, which is somewhat broken and might be deprecated/removed in future versions of C# …]