Monitor vs lock

后端 未结 9 2121
孤独总比滥情好
孤独总比滥情好 2020-11-27 11:42

When is it appropriate to use either the Monitor class or the lock keyword for thread safety in C#?

EDIT: It seems from th

相关标签:
9条回答
  • 2020-11-27 12:07

    lock is just shortcut for Monitor.Enter with try + finally and Monitor.Exit. Use lock statement whenever it is enough - if you need something like TryEnter, you will have to use Monitor.

    0 讨论(0)
  • 2020-11-27 12:08

    A lock statement is equivalent to:

    Monitor.Enter(object);
    try
    {
       // Your code here...
    }
    finally
    {
       Monitor.Exit(object);
    }
    

    However, keep in mind that Monitor can also Wait() and Pulse(), which are often useful in complex multithreading situations.

    Update

    However in C# 4 its implemented differently:

    bool lockWasTaken = false;
    var temp = obj;
    try 
    {
         Monitor.Enter(temp, ref lockWasTaken); 
         //your code
    }
    finally 
    { 
         if (lockWasTaken) 
                 Monitor.Exit(temp); 
    } 
    

    Thanx to CodeInChaos for comments and links

    0 讨论(0)
  • 2020-11-27 12:08

    The lock and the basic behavior of the monitor (enter + exit) is more or less the same, but the monitor has more options that allows you more synchronization possibilities.

    The lock is a shortcut, and it's the option for the basic usage.

    If you need more control, the monitor is the better option. You can use the Wait, TryEnter and the Pulse, for advanced usages (like barriers, semaphores and so on).

    0 讨论(0)
提交回复
热议问题