SemaphoreSlim误用导致锁失效的BUG

@果酱  May 28, 2024

BUG

internal class Program
{
   static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1,1);
   public async Task foo(CancellToken cancelltoken)
   {
      try{
         //超时会释放锁,进入后序代码执行,不会报错停止执行
         //被cancell会报错进入finally,此时并没有拿到锁,导致异常release
         await semaphoreSlim.WaitAsync(1000, cancelltoken);
         db.Select(....)
         ....
      }
      cache(Exeption ex){
         log.info(ex);
         throw;
      }
      finally{
         semaphoreSlim.release();
      }
   }
}

FIX

internal class Program
{
   static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1,1);
   public async Task foo(CancellToken cancelltoken)
   {
      //放到try...catch外面,没有拿到锁不能release
      await semaphoreSlim.WaitAsync(1000, cancelltoken);
      try{
         db.Select(....)
         ....
      }
      catch(Exception ex){
         log.info(ex);
         throw;
      }
      finally{
         semaphoreSlim.release();
      }
   }
}


demo
C#多线程十 信号量Semaphore/SemaphoreSlim的简单理解与运用


添加新评论