锁定多个线程中的变量 [英] Lock on a variable in multiple threads
问题描述
我是C#的新手,我想问一下我是否在MULTI THREADS(伪代码)中遇到这种情况:
I am very new to C# and I wanted to ask if I have this situation in MULTI THREADS (pseudo code):
public class ClassA
{
ClassB c = new ClassB();
public void someMethod()
{
c.myVar = 1;
// Some other stuff
c.myVar = 0;
}
}
public class ClassB
{
internal int myVar;
public void MethodA()
{
if(myVar = 1)
myVar = 0;
}
}
如果someMethod()
和MethodA()
可以在单独的线程中处于活动状态,则MethodA()
可以将if语句评估为true;否则,但是在设置myVar = 0
之前,someMethod()
设置myVar = 0
使得在MethodA()
中将myVar
设置为0是不正确的!
If someMethod()
and MethodA()
can be active in separate threads, then MethodA()
could evaluate the if statement as true; but before it sets myVar = 0
, someMethod()
sets myVar = 0
making it incorrect to have set myVar
to 0 in MethodA()
!!
基本上,如何锁定myVar
:
- 我可以在
myVar
的属性(设置,获取)上lock{}
- 我是否需要使用
Interlock
(尽管我还没有Interlock
的经验)?
- can I
lock{}
onmyVar
's property (set, get) - do I need to use
Interlock
(I have no experience yet ofInterlock
though)?
推荐答案
您应该创建一个允许锁定的私有对象:
You should create a private object that will allow for locking:
private readonly object _locker = new object();
然后在属性的get/set方法中,对其进行锁定:
Then in your property get/set methods, lock around it:
get { lock (_locker) { return this.myVar; } }
set { lock (_locker) { this.myVar = value; } }
确保您的方法也使用该锁:
Make sure your method uses the lock also:
public void MethodA()
{
lock(_locker)
{
if(myVar == 1)
myVar = 0;
}
}
这篇关于锁定多个线程中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!