Threading in C# , value types and reference types clarification? Threading in C# , value types and reference types clarification? multithreading multithreading

Threading in C# , value types and reference types clarification?


Neither thread simply "runs DoWork"; they run DoWork on a particular object. If the two threads are created targeting different instances, then mp and g will be completely separate fields. If the two threads are created targeting the same instance, then mp and g will be shared but it is not guaranteed that the threads will see changes made by the other thread unless you use synchronization or volatile access.

For example:

var obj = new SomeObject();Thread thread1 = new Thread(obj.DoWork);Thread thread2 = new Thread(obj.DoWork); // clearly targeting the same instance

vs

var obj = new SomeObject();Thread thread1 = new Thread(obj.DoWork);obj = new SomeObject();Thread thread2 = new Thread(obj.DoWork); // targeting a different instance

The local variables i and mp2 are strictly specific to each thread.

Additional note: even if they are separate fields/locals, if some of the code in the ... later reassigns mp or mp2 to refer to the same object, then they will be squabbling over the same object; the same synchronization / volatile rules will apply.


The variables g and mp are 'global' to the containing class, so these will be the same objects seen by both threads. i is a local variable that is declared in the DoWork event; subsequently this will only be 'visible' to the background/alternative thread.

They don't 'see' the same, so the static keyword in this case has no relevence.

I hope this helps.