Hi,
When an object is altered in a method that runs on a separate thread, the object is not altered on the calling thread (the thread that started the thread on which the method runs). However, if the class that defines the object is generic, the object gets altered on the calling thread. For example:
I have two classes:
public class Holder<T> { public T Value {get;set;} }
And
public class Holder2 { public String Value {get;set;} }
I have a third object called client which on method Change() sets the Value to something different on a separate thread:
static void main(string[] args)
{
Holder<String> test = new Holder<String>();
test.Set("original");
Client client = new client(test);
client.Change(test);
Console.WriteLine(test.Value);
// test.Value now returns "changed"
// But if test was of type Holder2, it would return "original"
}
So basically what client does is:
public class Client
{
Holder<String> test;
public Client(Holder<String> test)
{
this.test = test;
}
public void Change()
{
ThreadStart ts = new ThreadStart(Alter);
Thread t = new Thread(ts);
t.Start();
}
public void Alter()
{
test.Value = "changed";
}
}
However, If I change the Client class to instead take Holder2, which isn't generic it does no longer work. That is to say, test.Value would return "original". Can anyone please explain to me, why is that?