C# 读取和设置多线程的属性
我的项目有3个类和2个线程。当我访问创建线程的类的属性时,我得到了正确的值。我正在读的这门课开始了第二条线索。我想从这个新线程中读取第二个类的属性 当我在class1中设置值时,值是1,但class3中的值是0C# 读取和设置多线程的属性,c#,multithreading,instantiation,instance-variables,C#,Multithreading,Instantiation,Instance Variables,我的项目有3个类和2个线程。当我访问创建线程的类的属性时,我得到了正确的值。我正在读的这门课开始了第二条线索。我想从这个新线程中读取第二个类的属性 当我在class1中设置值时,值是1,但class3中的值是0 class test { public void main() { Class2 cl = new Class2; thread th = new thread(new threadstart(a.start)); th.s
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());
}
}
您有两个独立的
Class2
实例。在Class3
中创建的实例不知道在Class1
中创建的实例中的值是什么
如果您知道只需要处理test
属性的单个实例,可以将其设置为静态:
public static int Test { get; set; }
然后使用以下方法引用:
Class2.Test = 1;
另一方面,我不确定这是如何编译的,因为您有一个名为“test”的公共属性来访问
Class2
中的私有“test”变量。通常,人们将私有变量命名为\u test
(取决于您的个人偏好),或者,如果您的属性除了访问私有变量之外什么都不做,就完全省略私有变量。我会使用内置的.NET库来管理线程
按照这里的一些教程进行操作。这些对象使处理线程和等待结果变得更加容易。他们甚至为您提供线程安全对象
线程安全等价物:
Array,List
=>ConcurrencyBag
Dictionary
=>ConcurrentDictionary
您的意思是在test::main
中键入cl.start
而不是a.start