How can I write a conditional lock in C#? How can I write a conditional lock in C#? multithreading multithreading

How can I write a conditional lock in C#?


I think that question cries "race condition!". What if the condition turns from true to false shortly after the check, but before a thread enters the critical section of code? Or while a thread is in the process of executing it?


bool locked = false;if (condition) {    Monitor.Enter(lockObject);    locked = true;}try {    // possibly critical section}finally {    if (locked) Monitor.Exit(lockObject);}

EDIT: yes, there is a race condition unless you can assure that the condition is constant while threads are entering.


I'm no threading expert, but it sounds like you might be looking for something like this (double-checked locking). The idea is to check the condition both before and after acquiring the lock.

private static object lockHolder = new object();if (ActionIsValid()) {  lock(lockHolder) {    if (ActionIsValid()) {       DoSomething();        }  }}