【问题标题】:Reading and setting property multiple threads多线程读取和设置属性
【发布时间】:2013-08-09 10:37:56
【问题描述】:

我的项目有 3 个类和 2 个线程。当我访问创建线程的类的属性时,我得到了正确的值。我正在阅读的课程开始第二个线程。我想从这个新线程中读取第二类的属性。

当我在class1中设置值时,值为1,但class3中的值为0。

class test
{
    public void main()
    {
        Class2 cl = new Class2;
        thread th = new thread(new threadstart(a.start));
        th.start()

        cl.test=1;
    }
}

class Class2
{
    private int test;
    public int test
    {
        get { return test;}
        set {test = value;}
    }

    public void start()
    {
        Class3 cls = new Class3();
        thread th = new thread(new threadstart(cls.begin));
        th.start();
    }
}

class Class3
{
    public void begin()
    {
        Class2 cl = new Class2();
        MessageBox.show(cl.test.tostring());
    }
}

【问题讨论】:

  • 您的意思是在test::main 中输入cl.start 而不是a.start

标签: c# multithreading instantiation instance-variables


【解决方案1】:

您有两个单独的 Class2 实例。在Class3 中创建的实例不知道您在Class1 中创建的实例中的值是什么。

如果您知道您只想处理 test 属性的单个实例,则可以将其设为静态:

public static int Test { get; set; }

然后使用:

Class2.Test = 1;

顺便说一句,我不确定这是如何编译的,因为您有一个名为“test”的公共属性来访问Class2 中的私有“test”变量。通常,人们将私有变量命名为 _test(取决于您的个人喜好),或者如果您的属性除了访问私有变量之外什么都不做,则像我上面所做的那样完全省略私有变量.

【讨论】:

    【解决方案2】:

    我会使用内置的 .NET 库来管理线程。 Task Parallelism

    按照此处的一些教程进行操作。这些对象使处理线程和等待结果变得更加容易。他们甚至为您提供线程安全对象。

    线程安全等效项:

    Array,List => ConcurrencyBag<T>

    Dictionary<K, T> => ConcurrentDictionary<K, T>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-03
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      • 2010-10-11
      • 2014-06-22
      相关资源
      最近更新 更多