【问题标题】:Why does an instance of a generic class get altered on a separate thread when an instance of an ordinary class does not?为什么普通类的实例不会在单独的线程上更改泛型类的实例?
【发布时间】:2010-02-12 10:36:10
【问题描述】:

当在单独线程上运行的方法中更改对象时,不会在调用线程(启动该方法运行的线程的线程)上更改对象。 但是,如果定义对象的类是泛型的,则对象会在调用线程上被更改。例如:

我有两个班级:

public class Holder<T> { public T Value {get;set;} }

public class Holder2 { public String Value {get;set;} }

我有一个名为 client 的第三个对象,它在 Change() 方法上将 Value 设置为单独线程上的不同值:

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"
}

所以基本上客户所做的是:

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";
    }
    }

但是,如果我将 Client 类更改为使用 Holder2,这不是通用的,它将不再起作用。也就是说,test.Value 将返回“原始”。谁能给我解释一下,这是为什么?

【问题讨论】:

  • 但完整程序请演示问题(例如Set是什么?)
  • 这与泛型无关,而是与线程和时序有关。您根本不需要等待 Alter 方法完成。任何再现性都是偶然的。
  • 你是对的。我放入了一个 Thread.Sleep(2000),它给了 Alter 方法一些时间来完成。谢谢!

标签: c# .net generics multithreading


【解决方案1】:

由于您不使用锁定,因此存在可能解释您的观察结果的竞争条件。

另外:请说明你在调用client.Change(test)后如何显示变量;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 2023-03-19
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多