我在这里问了一个很糟糕的问题在多个线程中锁定变量 https://stackoverflow.com/questions/4081986/lock-on-a-variable-in-multiple-threads因此,为了清楚起见,我将在这里提出这个问题,并希望我能正确地提出这个问题。
classA
creates instance of classB
has methodA that can update & uses classB's myVar
has methodB that can update & uses classB's myVar
classB
has a variable myVar
方法和方法 B 都可以在单独的线程中运行(在主线程中的新线程中调用)。我如何确保这是线程安全的?
Use the lock
关键字来保护可由多个线程同时执行的代码。
public class ClassA
{
private ClassB b = new ClassB();
public void MethodA()
{
lock (b)
{
// Do anything you want with b here.
}
}
public void MethodB()
{
lock (b)
{
// Do anything you want with b here.
}
}
}
重要的是要注意lock
不保护或锁定语句中使用的对象实例。相反,该对象被用作识别代码段的一种方式,如果另一个部分使用该对象,则应阻止执行该代码段。same对象实例已经在执行。换句话说,您可以在中使用任何您喜欢的对象实例lock
声明,并且访问成员仍然是安全的ClassB
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)