Static field in class instance of the class is shared. Multiple threads modify the instance field values in the other thread it is visible, which is the default behavior clr. Add a static field ThreadStaticAttribute mark can change this default behavior.
ThreadStaticAttribute
Value indicates a static field is unique for each thread. With ThreadStaticAttribute marked static fields are not shared between threads. Each field has a separate thread of execution examples, and independently set and access to the field's value. If you access the field in a different thread, then the field will contain different values.
[ThreadStatic] public static int _field; public static int _field2;
// local variable new Thread(() => { for (int x = 0; x < 10; x++) { _field++; _field2++; //Console.WriteLine("Thread A: {0}", _field); Console.WriteLine("Thread A2: {0}", _field2); } }).Start(); new Thread(() => { for (int x = 0; x < 10; x++) { _field++; _field2++; //Console.WriteLine("Thread B: {0}", _field); Console.WriteLine("Thread B2: {0}", _field2); } }).Start();
analysis
Static variables have ThreadStatic mark, has its own copy in each thread.
The general static variables shared between processes.