I am re-factoring 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
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.
Static constructors are always thread safe. The runtime guarantees that a static constructor is only called once. So even if a type is called by multiple threads at the same time, the static constructor is always executed one time.
Thread SafetyStatic variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process. Hence, access to static variable is not thread safe.
Static constructors allow you to initialize static variables in a class, or do other things needed to do in a class after it's first referenced in your code. They are called only once each time your program runs. Instance constructors are the ones that are called whenever you create new objects (instances of classes).
A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.
If you are only incrementing a number, there is a special class (Interlocked) for just that...
http://msdn.microsoft.com/en-us/library/system.threading.interlocked.increment.aspx
Interlocked.Increment Method
Increments a specified variable and stores the result, as an atomic operation.
System.Threading.Interlocked.Increment(myField);
More information about threading best practices...
http://msdn.microsoft.com/en-us/library/1c9txz50.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With