views:

77

answers:

2
  • We know from the C# specification that reference read/writes are atomic. In a statement that accesses member of an object, will the reference also be accessed atomically? I think yes because it is also a kind of implicit reference read which the compiler must provide atomicity for while generating code for it.

  • In the same statement, accessing the object to access its member will this cause the objects reference held so it is not garbage collected when a new instance is created by another thread?

  • So, if we access members in a chain, will the leftmost objects reference is also be held so it is not garbage collected by other threads?

Consider the following code;

static SomeClass sharedVar;

void someMethod()
{
    SomeClass someLocalVar = sharedVar.memberX.memberY.a;
    operations on someLocalVar...
}

I am looking for official explanation about the subject, from MSDN library, C# specs, etc. or Microsoft people to make sure that I am not breaking something and everything is fine.

+3  A: 
  1. Yes, all reference reads are atomic.
  2. During a field read operation, a reference cannot be collected from the time the value is pushed onto the stack until the .ldfld command has completed. Otherwise it would allow the CLR to collect an object you were using. Having another thread create an instance of the value is unrelated to this problem.
  3. I'm not entirely sure what you mean by this last point, but I think you are worrying about garbage collection a bit too much. The CLR will not remove an object while you are still using it.
JaredPar
2. i mean if another thread assigns a new instance to sharedVar so causes the old reference disposed while this one is accessing the sharedVar.3. i mean when some point while a thread is executing the instructions for the statement SomeClass someLocalVar = sharedVar.memberX.memberY.a;and when memberY is read, another thread comes into action and assigns null or new object to sharedVar. i don't think that the reference will be disposed but i just hesitate and want to make myself sure with official documents, explanations?thanks.
lockedscope
A: 

You're worrying too much about GC. It will not remove any object that it is possible for you to reference & access at some point in the future. Only objects that are completely inaccessible will be removed.

thecoop