How to write conditional lock in C #?

7 answers
Action doThatThing = someMethod; if (condition) { lock(thatThing) { doThatThing(); } } else { doThatThing(); } 
+5
source share

I think this question yells "race condition!". What should I do if the condition goes from true to false right after checking, but before the stream gets to the critical section of the code? Or while the thread is in the process of executing it?

+9
source share
 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 if you can’t assure that the condition is constant when entering streams.

+7
source share

I'm not a thread specialist, but it looks like you might find something like this (double check). The idea is to check the status both before and after acquiring the lock.

 private static object lockHolder = new object(); if (ActionIsValid()) { lock(lockHolder) { if (ActionIsValid()) { DoSomething(); } } } 
+7
source share

In fact, in order to avoid the race condition, I would like to use ReaderWriterLockSlim here - to consider simultaneous access as a read lock and exclusive access as a write lock. Thus, if the conditions change, you will not have some inappropriate code still performing blind action in the region (under the false assumption that it is safe); bit verbose, but (formatted for space):

  if (someCondition) { lockObj.EnterReadLock(); try { Foo(); } finally { lockObj.ExitReadLock(); } } else { lockObj.EnterWriteLock(); try { Foo(); } finally { lockObj.ExitWriteLock(); } } 
+4
source share

Use the Double-Checked Lock Pattern as suggested above. what's the IMO trick :)

make sure your lock object is static as indicated in the not.that.dave.foley.myopenid.com example.

+2
source share

I assume you have code that looks something like this:

 private Monkey GetScaryMonkey(int numberOfHeads){ Monkey ape = null; lock(this) { ape = new Monkey(); ape.AddHeads(numberOfHeads); } return ape; } 

To make this condition, you could not just do this:

 private Monkey GetScaryMonkey(int numberOfHeads){ if ( numberOfHeads > 1 ) { lock(this) { return CreateNewMonkey( numberOfHeads ); } } return CreateNewMonkey( numberOfHeads ); } 

Should work, no?

+1
source share

All Articles