title: Correctly sharing variables between threads (.NET/VB.NET)
body: <p>I've been reading a lot of various blogs and StackOverflow questions to try to find an answer to my question and at the end I could not find anything so I thought to ask the question myself.</p>
  
  <p>I am building an application where I have a long running worker threads which perform some operations and places some results into variables during its run. The worker thread is constantly working and is constantly producing some results whereby I am only interested in the 'current' value of the result. At some point another thread will get the 'current' result of the worker thread run and do something with it. </p>
  
  <p>A simple implementation of such worker thread can be done like this:</p>
  
  <pre><code>Public Class Worker
  
      Private _result As DateTimeOffset?
  
      Public ReadOnly Property Result As DateTimeOffset?
          Get
              Return _result
          End Get
      End Property
  
  
      Public Sub ThreadMethod()
          ' Do something
          _result = x
          ' .
          ' .
          _result = y
          ' .
          ' .
          ' etc
      End Sub
  
  End Class
  </code></pre>
  
  <p>Now lets say I have I a consumer which wants to consume the result:</p>
  
  <pre><code>Public Class Consumer
  
      Private _worker As Worker
  
      Public Sub Consume()
          Dim result As DateTimeOffset?
          While True
              ' Do some work on your own
              ' .
              ' .
              ' Get current result
              result = _worker.Result
              ' Do something with result
  
          End While
      End Sub
  
  End Class
  </code></pre>
  
  <p>As far as I have understood how compilers work it seems logical that the compiler could make the <code>Property Result</code> inline and then optimize away the <code>_result</code> variable into a register and just read the same value over and over again.
  In C# I could mark the result as <code>volatile</code> and this (I think) would prevent such optimization but the keyword does not exist in VB.NET.
  The closest solution I could come up with is to use <code>Volatile.Write</code> and <code>Volatile.Read</code> methods. However those methods can not be used with <code>Nullable(Of DateTimeOffset)</code>.</p>
  
  <p>Note 1: Although this question seems to be related to weak/strong memory model and usage of memory barriers I do not believe that they have any impact in this scenario. That being said if somebody states that <code>Thread.MemoryBarrier()</code> would force the read/write to be from memory that it is also a good enough solution for me.</p>
  
  <p>Note 2: I am aware that there are other ways to solve the problem but I would like to know if the solution is possible (if the problem even exists, I am not even sure about that) for the described scenario.</p>