I wish to atomically increment a static variable and simultaneously assign the new value to an instance field in a lock-free manner. The objective is for each object to get a unique, incrementing id upon creation, such that there is no chance for two objects to get the same id.
Will the following code achieve this?
class MyClass
{
private static int currentOrderingId;
private int orderingId;
public MyClass()
{
Interlocked.Exchange(ref orderingId, Interlocked.Increment(ref currentOrderingId));
}
}