C# 异步锁 await async锁,lock,Monitor,SemaphoreSlim

异步方法内无法使用Monitor 和lock
所以只能用System.Threading.SemaphoreSlim了

            //Semaphore (int initialCount, int maximumCount);
            //initialCount代表还分配几个线程,比如是1,那就是还能允许一个线程继续跑锁起来的代码
            //maximumCount代表最大允许数,比如是1,那就是进去1个线程,就会锁起来
            System.Threading.SemaphoreSlim slimlock = new SemaphoreSlim(1, 1);
            await slimlock.WaitAsync();
            try
            {
                await Task.Delay(3000);
            }
            finally
            {
                slimlock.Release();
            }

而Monitor和lock只能用在非异步上面

//1.Monitor
object lockObject= new object();
bool acquiredLock = false;
try
{
    Monitor.TryEnter(lockObject, ref acquiredLock);
    if (acquiredLock)
    {

        // Code that accesses resources that are protected by the lock.
    }
    else
    {
    
        // Code to deal with the fact that the lock was not acquired.
    }
}
finally
{
    if (acquiredLock)
    {
        Monitor.Exit(lockObject);
    }
}

//2.Monitor lock
//Monitor
try
{
    Monitor.Enter(lockObject);
      // Code that accesses resources that are protected by the lock.
}
finally
{
    Monitor.Exit(lockObject);
}
//lock:

lock(lockObject)
{
     //Code that accesses resources that are protected by the lock.
}

上述2两个加锁的例子完全是等价的,都是在非异步的时候锁定某段代码

你可能感兴趣的:(C# 异步锁 await async锁,lock,Monitor,SemaphoreSlim)