lockedscope
lockedscope

Reputation: 983

Accessing object members and atomicity

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.

Upvotes: 3

Views: 302

Answers (2)

thecoop
thecoop

Reputation: 46098

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.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754675

  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.

Upvotes: 3

Related Questions