I need to create a Thread-safe static variable in C# .Net

后端 未结 7 1380
失恋的感觉
失恋的感觉 2020-12-17 18:01

ok, its a little more complicated than the question.

class A
{
   static int needsToBeThreadSafe = 0;

   public static void M1()
   {
     needsToBeThreadSa         


        
7条回答
  •  伪装坚强ぢ
    2020-12-17 18:20

    class A
    {
       static int needsToBeThreadSafe = 0;
       static object statObjLocker = new object();
    
       public static void M1()
       {
           lock(statObjLocker)
           {
              needsToBeThreadSafe = RandomNumber();
           }
       }
    
       public static void M2()
       {
           lock(statObjLocker)
           {
              print(needsToBeThreadSafe);
           }
       }
    }
    

提交回复
热议问题