zoukankan      html  css  js  c++  java
  • 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
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    Middleware
    Languages
    Errors
    Config
    CLI Console
    Linux远程复制文件
    CentOS下安装Gitlab
    Maven_POM配置结构
    Maven_POM配置详解
    MySQL索引背后的数据结构及算法原理
  • 原文地址:https://www.cnblogs.com/bruce1992/p/15066173.html
Copyright © 2011-2022 走看看