Should access to an immutable object be through a memory barrier in C #?

When an immutable object is updated in one thread and shares in a second thread (for example, as a field of a shared object), should the second thread not be synchronized?

Thread1:
=========
 x = new SomeObject()

Thread2
=========
if (x != null)
 x.DoSomething()

Should there be a memory barrier before x.DoSomething ()? Is it possible that assignment x in the first thread will never be visible for the second thread? What is the secure publishing template for .NET?

+5
source share
1 answer

Yes, it is possible that thread 2 will never see a nonzero x value with the code you wrote (depending on how the code is optimized). You do not need an explicit memory barrier. Just declare x mutable.

+2

All Articles