Monitor vs lock

后端 未结 9 2153
孤独总比滥情好
孤独总比滥情好 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条回答
  •  萌比男神i
    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

提交回复
热议问题