锁定多个线程中的变量 [英] Lock on a variable in multiple threads

查看:63
本文介绍了锁定多个线程中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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{} on myVar's property (set, get)
  • do I need to use Interlock (I have no experience yet of Interlock 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆