The most efficient way to do this is to use a lock operation with a lock. It will increment the counter and return the newly set value of the static counter at the same time (atomically)
class MyClass { static int _LastInstanceId = 0; private readonly int instanceId; public MyClass() { this.instanceId = Interlocked.Increment(ref _LastInstanceId); } }
In your original example, the lock (this) statement will not have the desired effect, because each individual instance will have a different "this" link, and therefore multiple instances can update the static member at the same time.
In a sense, constructors can be considered thread-safe because the reference to the object that is being built is not visible until the constructor completes, but it does not benefit from protecting the static variable.
(First, Mike Shull had a blocked bit)
Andrew 03 Sep '08 at 15:42 2008-09-03 15:42
source share