I have an object that I am accessing from two threads. One thread calls a long-running member function on the object that returns a value. The second thread updates the object used to produce that value.
I if I call Interlock.Exchange to replace the object from the second thread while the first thread is executing: 1. Will the old thread's self retain a reference to the original object. 2. Is there a risk that the original object is garbage collected?
import System;
import System.Threading;
import System.Generics;
class Example {
var mData = new String("Old");
public void LongFunction() {
Thread.Sleep(1000);
Console.WriteLine(mData);
}
public void Update() {
Interlocked.Exchange(ref mData, "Old");
}
}
class Program {
public static Main(string[] argv) {
var e = new Example();
var t = new Thread(new ThreadStart(e.LongFunction()));
t.Start();
e.Update();
}
}
Is this guaranteed to always print "Old"? Thanks.