C# lock,monitor,enter,tryenter,lockTaken

 class ThreadSafe
 {
     static readonly object _locker = new object();
     static int _val1 = 1, _val2 = 1;

     static void Go()
     {
         lock(_locker)
         {
             if(_val2!=0)
             {
                 Console.WriteLine(_val1 / _val2);
             }
             _val2 = 0;
         }
     }

     static void MonitorEnterExit()
     {
         Monitor.Enter(_locker);
         try
         {
             if(_val2!=0)
             {
                 Console.WriteLine(_val1 / _val2);
             }
             _val2 = 2;
         }
         finally
         {
             Monitor.Exit(_locker);
         }
     }

     bool lockTaken = false;
     void MonitorEnterRefLockTaken()
     {
         try
         {
             Monitor.Enter(_locker, ref lockTaken);
         }
        finally
         {
             if(lockTaken)
             {
                 Monitor.Exit(_locker);
             }
         }
     }

     void MonitorTryEnterLockTaken()
     {
         Monitor.TryEnter(_locker,1000,ref lockTaken);
         Monitor.Exit(_locker);
     }
 }

  

 

The lock is sugar syntact of Monitor,Enter,TryEnter,with timespan and lockTaken,then Monitor.Exit();

posted @ 2024-03-09 17:28  FredGrit  阅读(9)  评论(0编辑  收藏  举报