code_junkie

Difference between lock(locker) and lock(variable_which_I_am_using)

Nov 11th, 2011
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. class MyClass
  2. {
  3. private object m_Locker = new object();
  4. private Dicionary<string, object> m_Hash = new Dictionary<string, object>();
  5.  
  6. public void OptionA()
  7. {
  8. lock(m_Locker){
  9. // Do something with the dictionary
  10. }
  11. }
  12.  
  13. public void OptionB()
  14. {
  15. lock(m_Hash){
  16. // Do something with the dictionary
  17. }
  18. }
  19. }
  20.  
  21. lock (m_Hash)
  22. {
  23. // Across all threads, I can be in one and only one of these two blocks
  24. // Do something with the dictionary
  25. }
  26. lock (m_Hash)
  27. {
  28. // Across all threads, I can be in one and only one of these two blocks
  29. // Do something with the dictionary
  30. }
  31.  
  32. private object m_LockerA = new object();
  33. private object m_LockerB = new object();
  34.  
  35. lock (m_LockerA)
  36. {
  37. // It's possible this block is active in one thread
  38. // while the block below is active in another
  39. // Do something with the dictionary
  40. }
  41. lock (m_LockerB)
  42. {
  43. // It's possible this block is active in one thread
  44. // while the block above is active in another
  45. // Do something with the dictionary
  46. }
Add Comment
Please, Sign In to add comment