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
g
or each thread will have its own item ? ? ( value )Will they both see the same
mp
or each thread will have its own item ?? ( instance )Will they both see the same
i
or each thread will have its own item ? ( value )Will they both see the same
mp2
or 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... )
The variables
g
andmp
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 theDoWork
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.
Neither thread simply "runs
DoWork
"; they runDoWork
on a particular object. If the two threads are created targeting different instances, thenmp
andg
will be completely separate fields. If the two threads are created targeting the same instance, thenmp
andg
will be shared but it is not guaranteed that the threads will see changes made by the other thread unless you use synchronization orvolatile
access.For example:
vs
The local variables
i
andmp2
are strictly specific to each thread.Additional note: even if they are separate fields/locals, if some of the code in the
...
later reassignsmp
ormp2
to refer to the same object, then they will be squabbling over the same object; the same synchronization /volatile
rules will apply.