Accessing object members and atomicity
We know from the C# specification that reference read/writes are atomic. In a statement that accesses member of an ob开发者_JAVA技巧ject, 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.
- Yes, all reference reads are atomic.
- 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.
- 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.
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.
精彩评论