Заблокировать переменную в нескольких потоках

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;
     }
}

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()!!

Basically, how do I lock myVar:

  • can I lock{} on myVar's property (set, get)
  • do I need to use Interlock (I have no experience yet of Interlock though)?
7
задан Luiso 19 March 2018 в 17:26
поделиться