开发者

Why does an instance of a generic class get altered on a separate thread when an instance of an ordinary class does not?

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 i开发者_高级运维f 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?


Since you do not use locking there is a race-condition which might explain your observations.

Also: Please show how you display the variable after calling the client.Change(test);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜