Monitor vs lock

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

    Monitor is more flexible. My favorite use case of using monitor is when you don't want to wait for your turn and just skip:

    //already executing? forget it, lets move on
    if(Monitor.TryEnter(_lockObject))
    {
        //do stuff;
        Monitor.Exit(_lockObject);
    }
    

提交回复
热议问题