code_junkie

How can I write a conditional lock in C#?

Nov 11th, 2011
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. Action doThatThing = someMethod;
  2.  
  3. if (condition)
  4. {
  5. lock(thatThing)
  6. {
  7. doThatThing();
  8. }
  9. }
  10. else
  11. {
  12. doThatThing();
  13. }
  14.  
  15. private static object lockHolder = new object();
  16.  
  17. if (ActionIsValid()) {
  18. lock(lockHolder) {
  19. if (ActionIsValid()) {
  20. DoSomething();
  21. }
  22. }
  23. }
  24.  
  25. if (someCondition) {
  26. lockObj.EnterReadLock();
  27. try { Foo(); }
  28. finally { lockObj.ExitReadLock(); }
  29. } else {
  30. lockObj.EnterWriteLock();
  31. try { Foo(); }
  32. finally { lockObj.ExitWriteLock(); }
  33. }
  34.  
  35. bool locked = false;
  36. if (condition) {
  37. Monitor.Enter(lockObject);
  38. locked = true;
  39. }
  40. try {
  41. // possibly critical section
  42. }
  43. finally {
  44. if (locked) Monitor.Exit(lockObject);
  45. }
  46.  
  47. private Monkey GetScaryMonkey(int numberOfHeads){
  48. Monkey ape = null;
  49. lock(this) {
  50. ape = new Monkey();
  51. ape.AddHeads(numberOfHeads);
  52. }
  53. return ape;
  54. }
  55.  
  56. private Monkey GetScaryMonkey(int numberOfHeads){
  57. if ( numberOfHeads > 1 ) {
  58. lock(this) {
  59. return CreateNewMonkey( numberOfHeads );
  60. }
  61. }
  62. return CreateNewMonkey( numberOfHeads );
  63. }
Add Comment
Please, Sign In to add comment