Monitor vs lock

后端 未结 9 2169
孤独总比滥情好
孤独总比滥情好 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 11:56

    Eric Lippert talks about this in his blog: Locks and exceptions do not mix

    The equivalent code differs between C# 4.0 and earlier versions.


    In C# 4.0 it is:

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

    It relies on Monitor.Enter atomically setting the flag when the lock is taken.


    And earlier it was:

    var temp = obj;
    Monitor.Enter(temp);
    try
    {
       body
    }
    finally
    {
        Monitor.Exit(temp);
    }
    

    This relies on no exception being thrown between Monitor.Enter and the try. I think in debug code this condition was violated because the compiler inserted a NOP between them and thus made thread abortion between those possible.

提交回复
热议问题