c# – 为什么此代码中的锁不起作用?

栏目: ASP.NET · 发布时间: 7年前

内容简介:这里使用的锁是可重入的.它将阻止另一个线程进入监视器,但不会阻止持有锁的线程.翻译自:https://stackoverflow.com/questions/10099474/why-the-lock-in-this-code-is-not-working

我写了简单的代码(附加),我不明白为什么某些块上的锁没有锁定范围.

代码 :

object locker = new object();
    private void foo(int i)
    {
        Console.WriteLine( string.Format( "i is {0}", i ) );
        lock( locker )
        {
            while( true )
            {
                Console.WriteLine( string.Format( "i in while loop is {0}", i ) ) ;
                foo( ++i );
            }
        }
    }

我期望在while循环中调用foo方法将等待直到锁定器将被释放(更衣室范围) – 但是带有arg的foo的所有调用都可以进入锁定器块.

这里使用的锁是可重入的.它将阻止另一个线程进入监视器,但不会阻止持有锁的线程.

翻译自:https://stackoverflow.com/questions/10099474/why-the-lock-in-this-code-is-not-working


以上所述就是小编给大家介绍的《c# – 为什么此代码中的锁不起作用?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Linux Command Line

The Linux Command Line

William E. Shotts Jr. / No Starch Press, Incorporated / 2012-1-17 / USD 39.95

You've experienced the shiny, point-and-click surface of your Linux computer-now dive below and explore its depths with the power of the command line. The Linux Command Line takes you from your very ......一起来看看 《The Linux Command Line》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具