What type of locking mechanism does lock statement use

后端 未结 3 510
生来不讨喜
生来不讨喜 2021-01-18 10:53

Does the c# lock keyword use a \'yielding\', \'spin-locking\' or hybrid approach to handle contention?

So far my searches on the .net lock statement hasn\'t turned u

3条回答
  •  心在旅途
    2021-01-18 10:55

    lock (obj)
    {
    }
    

    was just syntactic sugar for Monitor.Enter in a try...finally.

    Monitor.Enter(obj);
    try
    {
    }
    finally
    {
        Monitor.Exit(obj);
    }
    

    It is now something a little better (Thanks to Mark and Adriano for keeping me current).

    bool locked = false;  
    try  
    {  
        Monitor.Enter(_syncRoot, ref locked);  
    }  
    finally  
    {  
        if (locked)  
            Monitor.Exit(_syncRoot);  
    } 
    

提交回复
热议问题