Monitor.TryEnter方法和lock语句的使用注意

xiaoxiao2021-02-28  17

在写代码时,习惯性的用了                            lock  (searchLock)             {                  .......................             } 刚开始也没发现有什么不妥,可后来发现效率上有点问题。原因是lock 会在外面等直到占用的线程退出下一个线程才能进去,当有大批量的数据访问时容易造成阻塞。而 Monitor.TryEnter无论有没有获取对象锁都会返回结果。于是将代码改为如下:              if  ( Monitor  .TryEnter(searchLock))             {                  try                 {                     obj =  LinkService .Search(count, search);                      CacheHelper .AddGroup(searchGroupName, key, obj, 30);                      CacheHelper .AddGroup(searchGroupName, key+ "_old"  , obj, 60);                 }                  finally                 {                      Monitor .Exit(searchLock);                 }             }              else             {                  obj =  CacheHelper .Get(key+ "_old"  )  as  List <Model.  xxx >;                   if  (obj ==  null  )                  {                      obj =  new  List  <Model.  xxx >();                  }             }
转载请注明原文地址: https://www.6miu.com/read-450001.html

最新回复(0)