Just add to the discussion (why not?): Yes, the static property is common to all instances of the class, regardless of the thread (if the support field is not marked with ThreadStatic , that is!). But yes, there are potential multithreading issues that you have to deal with when working with such properties. Here is the script that I think others get.
Consider this code:
int x = MyClass.StaticProperty; MyClass.StaticProperty = x + 1;
The foregoing is a very simple example of where a race condition can cause two threads to perform what should be two indivisible actions, but instead actually perform one action effectively.
To illustrate:
Thread 1 thread 2
int x = MyClass.StaticProperty; // Let say
int x = MyClass.StaticProperty; // this is 1.
MyClass.StaticProperty = x + 1; // OK, so x is
MyClass.StaticProperty = x + 1; // now ... 2.
Do you see the problem? Two threads could read the value of a property before anyone writes to it; and the value written depends on the value read, which was the same for both streams!
Simple scripts like the ones above have a convenient class provided in the System.Threading namespace that can make multi-threaded reads / writes pretty painless to implement: Interlocked . For example, to increase StaticProperty above in a thread-safe manner, you can update MyClass as follows:
class MyClass static int _staticProperty; public static int StaticProperty { get { return _staticProperty; } } public static int IncrementProperty() {
In more complex scenarios (i.e. when you do not just change simple numeric fields in a simple way), you may need to develop your own synchronization strategy, the most common of which is the presence of an assigned lock object and just lock on it for each operation you want lead atomically.
Dan tao
source share