Why is lock much slower than Monitor.TryEnter?

前端 未结 5 684
囚心锁ツ
囚心锁ツ 2021-02-07 03:06

Results

Lock: 85.3 microseconds

Monitor.TryEnter: 11.0 microseconds

Isn\'t the lock expanded into the same code?

Edit: Results with 1000 iteratio

5条回答
  •  半阙折子戏
    2021-02-07 03:31

    You can use .NET reflector to inspect the generated IL. The lock keyword uses Monitor.Enter instead of Monitor.TryEnter - here's the short answer to your question. Here's how your code looks like when disassembled and translated back to C#:

    public void Lock_Performance_Test()
    {
        Stopwatch csLock = Stopwatch.StartNew();
        int i = 0;
        while (i < 100)
        {
            object CS$2$0000;
            bool <>s__LockTaken0 = false;
            try
            {
                Monitor.Enter(CS$2$0000 = this.object1, ref <>s__LockTaken0);
                i++;
            }
            finally
            {
                if (<>s__LockTaken0)
                {
                    Monitor.Exit(CS$2$0000);
                }
            }
        }
        csLock.Stop();
        Stopwatch csMonitor = Stopwatch.StartNew();
        i = 0;
        while (i < 100)
        {
            if (Monitor.TryEnter(this.object1, TimeSpan.FromSeconds(10.0)))
            {
                try
                {
                    i++;
                }
                finally
                {
                    Monitor.Exit(this.object1);
                }
            }
        }
        csMonitor.Stop();
        Console.WriteLine("Lock: {0:f1} microseconds", csLock.Elapsed.Ticks / 10M);
        Console.WriteLine("Monitor.TryEnter: {0:f1} microseconds", csMonitor.Elapsed.Ticks / 10M);
    }
    

提交回复
热议问题