I am refactoring some code and am wondering about the use of a 'lock' in the instance constructor.
public class MyClass
{
private static Int32 counter = 0;
private Int32 myCount;
public MyClass()
{
lock(this)
{
counter++;
myCount = counter;
}
}
}
Please confirm
- Instance constructors are thread-safe.
- The lock statement prevents access to that code block, not to the static 'counter' member.
If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a 'MyClass' and changing the count before this one sets its count?
FYI - This class is not a singleton. Instances must simply be aware of their number.