After reading Jon Skeet article , and this article from msdn , I still have a question
Let’s say I have this code :
MyPerson mp = new MyPerson(); //Field
int g=0; //Field
public void DoWork ()
{
int i;
MyPerson mp2 = new MyPerson();
...
}
Now let’s say I have 2 threads. which runs DoWork. ( let’s ignore for now , race conditions)
-
Will they both see the same
gor each thread will have its own item ? ? ( value ) -
Will they both see the same
mpor each thread will have its own item ?? ( instance ) -
Will they both see the same
ior each thread will have its own item ? ( value ) -
Will they both see the same
mp2or each thread will have its own item ? ( instance ) -
if they both see the same , why would I need
static?
I’ve searched a lot about this topic , and couldn’t find any article which states : Different Threads ,ref types and value types… )
Neither thread simply “runs
DoWork“; they runDoWorkon a particular object. If the two threads are created targeting different instances, thenmpandgwill be completely separate fields. If the two threads are created targeting the same instance, thenmpandgwill be shared but it is not guaranteed that the threads will see changes made by the other thread unless you use synchronization orvolatileaccess.For example:
vs
The local variables
iandmp2are strictly specific to each thread.Additional note: even if they are separate fields/locals, if some of the code in the
...later reassignsmpormp2to refer to the same object, then they will be squabbling over the same object; the same synchronization /volatilerules will apply.