• 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两个加锁的例子完全是等价的,都是在非异步的时候锁定某段代码



    作者:牧场小明
    链接:https://www.jianshu.com/p/1609c50279ac
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    数据挖掘与R语言,数据分析,机器学习
    Linux下bash中关于日期函数date的格式及各种用法
    大数据之机器学习(11)
    unsolved 2 db2 issues
    时间是一剂良药,是制作“知识食物”不可或缺的材料
    b,B,KB,MB,GB
    学习数据结构要再学一遍c语言,害,加油吧
    栈(stack)
    堆(heap)
    js计算器(一)
  • 原文地址:https://www.cnblogs.com/bruce1992/p/15066173.html
Copyright © 2020-2023  润新知