0

If you have a construct like this, it seems possible according to the linked article (https://msdn.microsoft.com/en-us/magazine/jj883956.aspx paragraph Read Introduction) ...

var temp = myRef;
temp.DoSomething1();
//... at a later time
temp.DoSomething2();

... that temp variable is optimized away by the jitter by a read introduction.

Question is: Is there a way to guarantee that I really work with the copy of the reference and not with an intrduced read of the origianl reference. Since in my program myRef can change all the time by assigning a new object, I need to make sure, that I access the same object during the whole function whenever I need to do something with the object.

What about:

  • temp = Thread.VolatileRead(myRef)
  • temp = Volatile.Read(myRef)
  • temp = CompareExchange (myRef, null, null);

Can it still happen, that the jitter does call one of the read operations several times instead creating a copy of the reference?

YosiFZ
  • 7,792
  • 21
  • 114
  • 221
be_mi
  • 529
  • 6
  • 21
  • [Related](https://stackoverflow.com/questions/16162745/event-raising-and-read-introduction-in-net-4-5) (dealing with same article, I think the answer of using a volaitle read, however you wish to write it, is correct) – Damien_The_Unbeliever Feb 28 '19 at 07:09
  • It is a very poor article. It misrepresents what is really going on, omits important details, lacks concrete advice and what little is there is wrong. It has however one useful side-effect to the reader, it scares the bejeezus out of everybody that thinks that they can write multi-threaded code without taking care of synchronization explicitly. Always start out writing threaded code with the `lock` keyword. If a concurrency analyzer shows that it became a bottleneck then micro-optimize with the Volatile or Interlocked classes and a lot of testing. – Hans Passant Feb 28 '19 at 09:24

0 Answers0