How to lock a variable used in multiple threads

前端 未结 6 2276
花落未央
花落未央 2021-02-13 02:47

I have asked a question badly over here Lock on a variable in multiple threads so for clarity I am going to ask it here and hope I can ask it correctly.

classA
          


        
6条回答
  •  心在旅途
    2021-02-13 03:04

    Use the lock keyword to guard code that can be executed simultaneously by more than one thread.

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

    It is important to note that lock does not guard or lock the object instance used in the statement. Instead, the object is used as a way to identify a section of code that should be prevented from executing if another section using the same object instance is already executing. In other words, you could use any object instance you like in the lock statements and it would still be safe to access members of ClassB.

提交回复
热议问题